前言:在程序发版之后,会偶发地出现消息找不到而导致的Crash(unrecognized selector sent to class ),最知名地后台返回null对象。我们可能判断不严谨,当做字典或数组处理,由于OC的动态性,就会发生错误。诚然,良好地代码逻辑可以避免这些问题。但是对于已经非我们自己写地代码,或者其他地SDK引起地问题,让我们防不胜防。所以,在Release下添加一个方法找不地防护还有很有作用地,至少保证不Crash,还可以把错误统计,方便后续地维护!
OC是消息机制,方法调用就是消息发送,这个流程不清楚的同学可以看看我前面的文章。当一个消息找不到时候就会进行消息转发。这时,有三次拯救地机会。
- 首先调用 +(BOOL)resolveInstanceMethod:(SEL)sel或者+ (BOOL)resolveClassMethod:(SEL)sel
给我们一次动态实现的机会,但是这个不合适,这样会使类添加一个这个方法,我们也不知道方法地具体实现 - 调用-(id)forwardingTargetForSelector:(SEL)aSelector
给我们一次转发给其他对象,如果返回一个非nil.消息将会转发给该对象.这个也不合适,因为我们也不知道要发给谁处理 - 调用- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector方法来获取这个选择子的方法签名.然后在- (void)forwardInvocation:(NSInvocation *)anInvocation处理,这个就是我们想用的。就是要HOOK这两个方法。
核心原理,利用Method-Swizzling达到HOOK这两个动态解析方法,为我所用。废话不多说,上代码,只所以写在Load方法里面是因为load方法会在启动之前自动的调用。用dispatch_once防止有人手动调用load方法,防止再次交换就等于没有交换。
+ (void)load {
static dispatch_once_t onceToken1;
dispatch_once(&onceToken1, ^{
Class class = [self class];
SEL originalSelector = @selector(forwardInvocation:);
SEL swizzledSelector = @selector(jessica_forwardInvocation:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (success) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
static dispatch_once_t onceToken2;
dispatch_once(&onceToken2, ^{
Class class = [self class];
SEL originalSelector = @selector(methodSignatureForSelector:);
SEL swizzledSelector = @selector(jessica_methodSignatureForSelector:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (success) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
接下来就是一个有错误的实现方法,原理非常简单,jessica_methodSignatureForSelector一定不能返回nil。所以当他解析不了地是时候强行给他一个NSMethodSignature,之所以这个写是因为苹果地编码规则。jessica_forwardInvocation是能响应就去处理,响应不了就不处理。代码如下
- (void)jessica_forwardInvocation:(NSInvocation *)anInvocation {
if ([self respondsToSelector:anInvocation.selector]) {
[anInvocation invokeWithTarget:self];
}
}
- (NSMethodSignature *)jessica_methodSignatureForSelector:(SEL)aSelector {
NSMethodSignature *methodSignature = [[self class] instanceMethodSignatureForSelector:aSelector];
if (methodSignature == nil) {//这里是关键
methodSignature = [NSMethodSignature signatureWithObjCTypes:"@^v^c"];
}
return methodSignature;
}
高高兴兴地集成到代码里面,但是还没等这个发挥作用,每次弹起键盘就会crash。如果我们只看左面地调用栈因为是UIKit框架,我们啥也看到,这时候可以用LLDB指令,输入bt指令,这样地调用栈才能解决问题,发现问题出现在这个UIKeyboardInputManagerClient身上,这个类调用methodSignatureForSelector这个方法,然说得到是一个nil。我猜想是这个类也做了消息转发,一开始我地想法非常简单,我判断一下这个类,是这个类我就不给他做解析了,让他还是调用原来地方法,果然可行,但是这样地方法并不好,因为这样地类可能还会有,可能系统升级也会多。所以不能写死,这时候runtime又有用了,我可以利用runtime,去查询一下该类是否重写过methodSignatureForSelector这个方法,如果重写过我就给你不去处理了。方便大家集成,我就上完整代码了!
.h文件
#import
@interface NSObject (JessicaMessageForwarding_h)
//是否重写了 methodSignatureForSelector
@property (assign, nonatomic) BOOL isOverriMethodSignatureForSelector;
//是否重写了forwardInvocation
@property (assign, nonatomic) BOOL isOverriForwardInvocation;
@end
.m文件
#import "NSObject+JessicaMessageForwarding_h.h"
#import
@implementation NSObject (JessicaMessageForwarding_h)
+ (void)load {
static dispatch_once_t onceToken1;
dispatch_once(&onceToken1, ^{
Class class = [self class];
SEL originalSelector = @selector(forwardInvocation:);
SEL swizzledSelector = @selector(jessica_forwardInvocation:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (success) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
static dispatch_once_t onceToken2;
dispatch_once(&onceToken2, ^{
Class class = [self class];
SEL originalSelector = @selector(methodSignatureForSelector:);
SEL swizzledSelector = @selector(jessica_methodSignatureForSelector:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (success) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
#pragma mark - Method Swizzling
- (void)jessica_forwardInvocation:(NSInvocation *)anInvocation {
if (self.isOverriForwardInvocation) {
return [self jessica_forwardInvocation:anInvocation];
}
if ([self respondsToSelector:anInvocation.selector]) {
[anInvocation invokeWithTarget:self];
}
}
- (NSMethodSignature *)jessica_methodSignatureForSelector:(SEL)aSelector {
if (self.isOverriMethodSignatureForSelector) {
return [self jessica_methodSignatureForSelector:aSelector];
}
NSMethodSignature *methodSignature = [[self class] instanceMethodSignatureForSelector:aSelector];
if (methodSignature == nil) {
#warning 诸如UIKeyboardInputManagerClient 这个类自己重写了 methodSignatureForSelector方法, 就得遵循自己地方法
self.isOverriMethodSignatureForSelector = NO;
self.isOverriForwardInvocation = NO;
for (NSString *methodStr in [self getAllMethodArray]) {
if ([methodStr isEqualToString:@"methodSignatureForSelector:"]) {
self.isOverriMethodSignatureForSelector = YES;
}
if ([methodStr isEqualToString:@"forwardInvocation:"]) {
self.isOverriForwardInvocation = YES;
}
}
if (self.isOverriMethodSignatureForSelector) {
return [self jessica_methodSignatureForSelector:aSelector];
}
methodSignature = [NSMethodSignature signatureWithObjCTypes:"@^v^c"];
}
return methodSignature;
}
-(NSArray *)getAllMethodArray{
u_int count;
NSMutableArray *arrayM = [NSMutableArray array];
Method *mothList_f = class_copyMethodList([self class],&count) ;
for (int i = 0; i < count; i++) {
Method temp_f = mothList_f[i];
SEL name_f = method_getName(temp_f);
const char * name_s = sel_getName(name_f);
[arrayM addObject:[NSString stringWithUTF8String:name_s]];
}
free(mothList_f);
return arrayM.copy;
}
-(BOOL)isOverriMethodSignatureForSelector{
NSNumber* vale = objc_getAssociatedObject(self, @selector(isOverriMethodSignatureForSelector));
return [vale boolValue];
}
-(BOOL)isOverriForwardInvocation{
NSNumber* vale = objc_getAssociatedObject(self, @selector(isOverriForwardInvocation));
return [vale boolValue];
}
-(void)setIsOverriMethodSignatureForSelector:(BOOL)vale{
objc_setAssociatedObject(self, @selector(isOverriMethodSignatureForSelector), [NSNumber numberWithBool:vale], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(void)setIsOverriForwardInvocation:(BOOL)vale{
objc_setAssociatedObject(self, @selector(isOverriForwardInvocation), [NSNumber numberWithBool:vale], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
建议大家集成之前多测试几个页面,没问题最好只在release下生效,如果在您地代码里面不兼容,发生异常。请与我联系,我会尽我所能地去完善。如果涉及到runime不懂地地方可以看看我原来地帖子,也可以与我交流,感谢您地阅读。
补充:之前我说的可以错误统计,就是在 methodSignature = [NSMethodSignature signatureWithObjCTypes:"@vc"]; 这个代码地时候添加一些保存上传地逻辑,把类名,方法名,当时地调用堆栈上传就好。