對象 p? p對象方法Method_list中沒有相關(guān)方法時 的消息查找 步驟
1.動態(tài)方法解析--添加方法實現(xiàn) (注意:這個方法會調(diào)用多次 最好不要用在消息轉(zhuǎn)發(fā))
對象方法
+ (BOOL)resolveInstanceMethod:(SEL)sel{
? ? NSString*method =NSStringFromSelector(sel);
? ? if([methodisEqualToString:@"sendMessage:"]) {
?? ? ? return? class_addMethod(self, sel, (IMP)sendIMP,"V@:@");
? ? }
? ? return NO;
}
voidsendIMP(idself,SEL_cmd,NSString*msg){
? ? NSLog(@"msg = %@",msg);
}
類方法
+(BOOL)resolveClassMethod:(SEL)sel{
? ? ? ? NSString*method =NSStringFromSelector(sel);
? ? if([methodisEqualToString:@"testMessage"]) {
//? ? ? ? NSString *className = NSStringFromClass([animal class]);
//? ? ? ? id is = objc_getClass([className UTF8String]);
? ? ? ? return? class_addMethod(object_getClass([animal class]), sel, (IMP)sendf, "V@:");
? ? ? ? }
? ? ? ? returnNO;
}
void sendf(id self,SEL _cmd){
? ? NSLog(@"messgae");
}
2.快速轉(zhuǎn)發(fā)
對象方法
- (id)forwardingTargetForSelector:(SEL)aSelector{
? ? NSString*method =NSStringFromSelector(aSelector);
? ? if([methodisEqualToString:@"testMessage"]) {
? ? ? ? return[Personnew];
? ? }
? ? return [super forwardingTargetForSelector:aSelector];
}
類方法
+ (id)forwardingTargetForSelector:(SEL)aSelector{
? ? NSString*method =NSStringFromSelector(aSelector);
? ? if([methodisEqualToString:@"testMessage"]) {
? ? ? ? return[Personclass];
? ? }
? ? return [super forwardingTargetForSelector:aSelector];
}
3.正常消息轉(zhuǎn)發(fā)(慢速轉(zhuǎn)發(fā))
//先簽名方法? ?動態(tài)綁定sel(方法名稱指針)-> IMP(方法實現(xiàn)指針)
- (NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector{
? ? NSString*method =NSStringFromSelector(aSelector);
? ? if([methodisEqualToString:@"sendMessage:"]) {
? ? ? ? return [NSMethodSignature signatureWithObjCTypes:"V@:@"];
? ? }
? ? return [super methodSignatureForSelector:aSelector];
}
//
- (void)forwardInvocation:(NSInvocation*)anInvocation{
? ? SELsel = [anInvocationselector];
? ? Person*p = [Personnew];
? ? if ([p respondsToSelector:sel]) {
? ? ? ? [anInvocationinvokeWithTarget:p];
? ? }else{
? ? ? ? [superforwardInvocation:anInvocation];
? ? }
}
4.////未找到方法
- (void)doesNotRecognizeSelector:(SEL)aSelector{
? ? NSLog(@"no selector");
}
5,消息轉(zhuǎn)發(fā)直接調(diào)用 方法簽名的
Person *p =[[Person alloc]init];
? ? NSMethodSignature*methodSign = [pmethodSignatureForSelector:@selector(sendMessage:)];
? ? NSInvocation*invocation = [NSInvocationinvocationWithMethodSignature:methodSign];
? ? invocation.target= p;
? ? invocation.selector=@selector(sendMessage:);
? ? NSString *str = @"invocation";
? ? [invocationsetArgument:&stratIndex:2];2——表示sendMessage:方法的第3個參數(shù)
? ? [invocationinvoke];