Created
November 12, 2016 13:03
-
-
Save swiftcafex/1de52fc40e2cdf07463668258c728979 to your computer and use it in GitHub Desktop.
消息转发示例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Person 本身没有实现 sayHello, 转发到内部实例中。 | |
@interface Person : NSObject | |
- (void) sayHello; | |
@end | |
@implementation Person { | |
InternalPerson *_iPerson; | |
} | |
- (instancetype)init { | |
self = [super init]; | |
if(self) { | |
_iPerson = [[InternalPerson alloc] init]; | |
} | |
return self; | |
} | |
- (void)forwardInvocation:(NSInvocation *)anInvocation | |
{ | |
//转发消息 | |
[anInvocation invokeWithTarget:_iPerson]; | |
} | |
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { | |
//返回消息签名 | |
NSMethodSignature* signature = [super methodSignatureForSelector:aSelector]; | |
if (!signature) { | |
signature = [_iPerson methodSignatureForSelector:aSelector]; | |
} | |
return signature; | |
} | |
@end | |
//InternalPerson 为实际的消息接收实例 | |
@interface InternalPerson : NSObject | |
- (void) sayHello; | |
@end | |
@implementation InternalPerson | |
- (void)sayHello { | |
//实际的消息接受者 | |
NSLog(@"hello world"); | |
} | |
@end | |
//程序入口 | |
int main() { | |
Person *person = [[Person alloc] init]; | |
[person sayHello]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment