Create a gist now

Instantly share code, notes, and snippets.

消息转发示例
//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