消息转发机制:当对象调用某个方法时,该方法没有实现,系统会通过消息转发来查找方法的实现。
下图为消息转发查找过程:

查找顺序优先级:
resolveInstanceMethod > forwardingTargetForSelector > forwardInvocation。
只有优先级高的方法未能处理或未定义时,系统才会从优先级低的方法开始查找。
首先,定义一个Person类,方法run并且.m文件中未实现该方法。

1.解析实例方法.
+ (BOOL)resolveInstanceMethod:(SEL)sel;

resolveInstanceMethod 方法中可以通过运行时动态添加方法来实现处理。最终run方法的实现由runIMP执行。
2.消息快速转发
- (id)forwardingTargetForSelector:(SEL)aSelector;

该方法中,可以引用Animation类来实现消息转发,前提是Animation类定义并实现run方法。


3,标准消息转发
- (void)forwardInvocation:(NSInvocation*)anInvocation;
- (NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector;

网友评论