#import "ViewController.h"
#import <objc/runtime.h>
#import "AppDelegate.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 调用一个没有实现的方法
[self performSelector:@selector(haha)];
}
/*处理不能识别的方法,会经历如下步骤,前一个步骤走不通的时候就会走下一个步骤*/
#if 1 //step1:决议机制,是否为该sel动态的添加一个方法实现
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
NSString *selname = NSStringFromSelector(sel);
if ([selname isEqualToString:@"haha"]) {
class_addMethod(self, sel, class_getMethodImplementation([AppDelegate class], @selector(haha)), method_getTypeEncoding(class_getInstanceMethod([AppDelegate class], @selector(haha))));
return YES;
}
return [super resolveInstanceMethod:sel];
}
- (void)oklala {
NSLog(@"oklala");
}
#endif
#if 1 // step2:转发给其它的对象处理
- (id)forwardingTargetForSelector:(SEL)aSelector
{
return [[AppDelegate alloc] init];
}
#endif
#if 1 // step3: 封装成NSInvocation对象转发处理,系统默认是调用doesNotRecognizeSelector,重写forwardInvocation:方法同时必需重写methodSignatureForSelector:(构造NSInvocation对象必需先有一个NSMethodSignature对象),
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
NSLog(@"~~~~%@", [anInvocation description]);
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
NSLog(@"%@", NSStringFromSelector(aSelector));
NSMethodSignature *sig = [NSMethodSignature signatureWithObjCTypes:"@@:"];
return sig;
}
#endif
@end