From 87351a45ad78c2c55f38692c447dec8603c441b6 Mon Sep 17 00:00:00 2001 From: chengxun Date: Thu, 13 Apr 2017 17:35:47 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=9C=AA=E8=AF=86=E5=88=AB?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E5=AF=BC=E8=87=B4=E7=9A=84crash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AvoidCrash/NSObject+AvoidCrash.m | 47 ++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/AvoidCrash/NSObject+AvoidCrash.m b/AvoidCrash/NSObject+AvoidCrash.m index 0513a49..854f344 100644 --- a/AvoidCrash/NSObject+AvoidCrash.m +++ b/AvoidCrash/NSObject+AvoidCrash.m @@ -27,9 +27,52 @@ + (void)avoidCrashExchangeMethod { //setValuesForKeysWithDictionary: [AvoidCrash exchangeInstanceMethod:[self class] method1Sel:@selector(setValuesForKeysWithDictionary:) method2Sel:@selector(avoidCrashSetValuesForKeysWithDictionary:)]; + + [AvoidCrash exchangeInstanceMethod:[self class] method1Sel:@selector(forwardingTargetForSelector:) method2Sel:@selector(avoid_forwardingTargetForSelector:)]; }); - - + +} + +- (id)avoid_forwardingTargetForSelector:(SEL)aSelector{ + NSString * selStr = NSStringFromSelector(aSelector); + /** 这里主要是判断方法存在或者方法是系统实现的私有方法 */ + if([self isExistSelector:aSelector inClass:[self class]] || [selStr hasPrefix:@"_"]){ + return [self avoid_forwardingTargetForSelector:aSelector]; + }else{ + + Class stubProxy = NSClassFromString(@"stubProxy"); + if(!stubProxy){ + stubProxy = objc_allocateClassPair([NSObject class], "stubProxy", 0); + objc_registerClassPair(stubProxy); + } + class_addMethod(stubProxy, aSelector, [self unrecognizedImplementation:aSelector], [selStr UTF8String]); + Class StubProxy = [stubProxy class]; + id instance = [[StubProxy alloc]init]; + return instance; + } +} + +- (BOOL)isExistSelector:(SEL)aSelector inClass:(Class)currentClass{ + BOOL isExist = NO; + unsigned int methodCount = 0; + Method * methods = class_copyMethodList(currentClass, &methodCount); + for (int i = 0; i