首页 > 其他 > 详细

Message Forwarding

时间:2014-02-17 15:34:40      阅读:413      评论:0      收藏:0      [点我收藏+]

Message Forwarding

  If you send a message to an object that does not handle that message, before announcing an error the runtime sends the object a forwardInvocation: message with an NSInvocation object as its sole argument—the NSInvocation object encapsulates the original message and the arguments that were passed with it.

  forwardInvocation方法可以帮助我们轻松的实现完美转发。

bubuko.com,布布扣
1 - (void)forwardInvocation:(NSInvocation *)anInvocation
2 {
3     if ([someOtherObject respondsToSelector:
4             [anInvocation selector]])
5         [anInvocation invokeWithTarget:someOtherObject];
6     else
7         [super forwardInvocation:anInvocation];
8 }
bubuko.com,布布扣

  forwarding实际上提供了一种多生继承的变相实现。

  bubuko.com,布布扣

  Although forwarding mimics inheritance, the NSObject class never confuses the two. Methods like respondsToSelector: and isKindOfClass: look only at the inheritance hierarchy, never at the forwarding chain. If, for example, a Warrior object is asked whether it responds to a negotiate message, 

1 if ( [aWarrior respondsToSelector:@selector(negotiate)] )
2     ...

  the answer is NO, even though it can receive negotiate messages without error and respond to them.

  如果想让respondsToSelector对代理的方法也返回YES,可以按如下实现:

bubuko.com,布布扣
 1 - (BOOL)respondsToSelector:(SEL)aSelector
 2 {
 3     if ( [super respondsToSelector:aSelector] )
 4         return YES;
 5     else {
 6         /* Here, test whether the aSelector message can     *
 7          * be forwarded to another object and whether that  *
 8          * object can respond to it. Return YES if it can.  */
 9     }
10     return NO;
11 }
bubuko.com,布布扣

  if an object forwards any remote messages it receives, it should have a version of methodSignatureForSelector: that can return accurate descriptions of the methods that ultimately respond to the forwarded messages

bubuko.com,布布扣
1 - (NSMethodSignature*)methodSignatureForSelector:(SEL)selector
2 {
3     NSMethodSignature* signature = [super methodSignatureForSelector:selector];
4     if (!signature) {
5        signature = [surrogate methodSignatureForSelector:selector];
6     }
7     return signature;
8 }
bubuko.com,布布扣

  

Message Forwarding

原文:http://www.cnblogs.com/tekkaman/p/3551928.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!