消息转发
2019-12-12 本文已影响0人
zzL丶
1.动态方法解析
+(void)load {
Method oldMethod = class_getInstanceMethod(self, @selector(reloadData));
Method newMethod = class_getInstanceMethod(self, @selector(lj_reloadData));
method_exchangeImplementations(oldMethod, newMethod);
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
NSString *methodName = NSStringFromSelector(sel);
if ([methodName isEqualToString:@"sendMessage:"]) {
return class_addMethod(self, sel, (IMP)sendMsg, "v@:@");
}
return NO;
}
2.备用接收者
- (id)forwardingTargetForSelector:(SEL)aSelector {
NSString *methodName = NSStringFromSelector(aSelector);
if ([methodName isEqualToString:@"sendMessage:"]) {
NSLog(@"备用接受者 ");
return [Message1 new];
}
return [super forwardingTargetForSelector:aSelector];
}
3.完整消息转发
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
NSString *methodName = NSStringFromSelector(aSelector);
if ([methodName isEqualToString:@"sendMessage:"]) {
return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
}
return [super methodSignatureForSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation {
SEL sel = [anInvocation selector];
Message1 *tempObj = [Message1 new];
if ([tempObj respondsToSelector:sel]) {
[anInvocation invokeWithTarget:tempObj];
}else {
[super forwardInvocation:anInvocation];
}
[super forwardInvocation:anInvocation];
}
4.报错
- (void)doesNotRecognizeSelector:(SEL)aSelector {
NSLog(@"找不到方法");
}