Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 45 additions & 2 deletions AvoidCrash/NSObject+AvoidCrash.m
Original file line number Diff line number Diff line change
Expand Up @@ -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<methodCount;i++ ) {
Method tmp = methods[i];
SEL sel = method_getName(tmp);
NSString * methodName = NSStringFromSelector(sel);
if([methodName isEqualToString:NSStringFromSelector(aSelector)]){
isExist = YES;
break;
}
}
return isExist;
}

- (IMP)unrecognizedImplementation:(SEL)aSelector{
IMP imp = imp_implementationWithBlock(^(){
NSLog(@"Function:%@ unrecognizeMethod resolved",NSStringFromSelector(aSelector));
});
return imp;
}


Expand Down