消息转发机制
之前想了解runtime的先关知识,无意中发现了消息转发机制,就自己动手写了些。
如上图所示:在oc中调用方法时,本类及父类找不到此方法时,有如下步骤。
要重写一下方法。
第一步:尝试动态方法解析
- voiddynamicMethod(idself,SEL_cmd)
- {
- printf("SEL%sdidnotexist\n",sel_getName(_cmd));
- }
- +(BOOL)resolveInstanceMethod:(SEL)aSEL
- {
- class_addMethod([selfclass],aSEL,(IMP)dynamicMethod,"[email protected]:");
- returnYES;
- }
第二步:如果第一步返回NO,则进行【尝试快速消息转发】
- -(id)forwardingTargetForSelector:(SEL)aSelector
- {
- Proxy*p=[[Proxyalloc]init];
- if([prespondsToSelector:aSelector])
- {
- returnp;
- }
- returnnil;
- }
第三步:如果第第二步返回nil,则进行【尝试标准消息转发】
- //检测此消息是否有效。
- -(NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector
- {
- return[ProxyinstanceMethodSignatureForSelector:aSelector];
- }
- -(void)forwardInvocation:(NSInvocation*)anInvocation
- {
- SELname=[anInvocationselector];
- NSLog(@">>forwardInvocationforselector%@",NSStringFromSelector(name));
- Proxy*proxy=[[Proxyalloc]init];
- if([proxyrespondsToSelector:name]){
- [anInvocationinvokeWithTarget:proxy];
- }
- else{
- [superforwardInvocation:anInvocation];
- }
- }
注:
调用函数:
- [fooperformSelector:@selector(MissMethod)];
Proxy类
- @implementationProxy
- -(void)MissMethod
- {
- NSLog(@">>MissMethod()calledinProxy.");
- }
- @end