1 重载 resolveInstanceMethod:
和 resolveClassMethod:
方法动态添加实例方法实现和类方法实现
+ (BOOL)resolveInstanceMethod:(SEL)sel { if (sel == @selector(setName:)) { class_addMethod([self class], sel, (IMP)setName, "v@:@"); return YES; }else if (sel == @selector(name)){ class_addMethod([self class], sel, (IMP)getName, "@@:"); return YES; } return [super resolveInstanceMethod:sel]; }
2 消息转发机制执行前,Runtime 系统允许我们替换消息的接收者为其他对象。通过 - (id)forwardingTargetForSelector:(SEL)aSelector
方法。
- (id)forwardingTargetForSelector:(SEL)aSelector { if(aSelector == @selector(mysteriousMethod:)){ return alternateObject; } return [super forwardingTargetForSelector:aSelector]; }
3 完整消息转发阶段
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { if(aSelector == @selector(testMethod)) { return [NSMethodSignature signatureWithObjCTypes:"v@:"]; } return nil; } -(void)forwardInvocation:(NSInvocation *)anInvocation { if (anInvocation.selector == @selector(testMethod)) { TestModelHelper1 *h1 = [[TestModelHelper1 alloc] init]; TestModelHelper2 *h2 = [[TestModelHelper2 alloc] init]; [anInvocation invokeWithTarget:h1]; [anInvocation invokeWithTarget:h2]; } }
forwardingTargetForSelector仅支持一个对象的返回,也就是说消息只能被转发给一个对象
forwardInvocation可以将消息同时转发给任意多个对象