以发送sendMessage:带参方法为例
1、动态方法解析
+ (BOOL)resolveInstanceMethod:(SEL)sel{
//动态方法解析
NSString*methodName =NSStringFromSelector(sel);
if([methodNameisEqualToString:@"sendMessage:"]) {
class_addMethod(self, sel, (IMP)sendMessage,"v@:@");
}
return NO;
}
2、快速转发
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
return NO;
}
backUpPerson是备份类方法
- (id)forwardingTargetForSelector:(SEL)aSelector
{
//快速查找
NSString*methodName =NSStringFromSelector(aSelector);
if([methodName isEqualToString:@"sendMessage:"]) {
return [backUpPerson new];
}
return [super forwardingTargetForSelector:aSelector];
}
3、慢速转发分两步
a、方法签名 b、消息转发
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
return NO;
}
- (id)forwardingTargetForSelector:(SEL)aSelector
{
[super forwardingTargetForSelector:aSelector];
}
//方法签名
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
NSString*methodName =NSStringFromSelector(aSelector);
if([methodName isEqualToString:@"sendMessage:"]) {
return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
}
return [super methodSignatureForSelector:aSelector];
}
//消息转发
- (void)forwardInvocation:(NSInvocation*)anInvocation
{
SELsel = [anInvocation selector];
backUpPerson *tempObj = [backUpPerson new];
if([tempObj respondsToSelector:sel]) {
[anInvocation invokeWithTarget:tempObj];
}else{
[super forwardInvocation:anInvocation];
}
}
三者都找不到方法时,最后调用
- (void)doesNotRecognizeSelector:(SEL)aSelector
{
NSLog(@"找不到方法");
}
网友评论