runtime 方法交换

为 NSString 重写 hasPrefix: 方法实现(交换方法)

@implementationNSString (myString)
+(void)load{
    Class class =NSClassFromString(@"__NSCFString");
    Methodm1 =class_getInstanceMethod(class,@selector(hasPrefix:));
    Methodm2 =class_getInstanceMethod(class,@selector(my_hasPrefix:));
    method_exchangeImplementations(m1, m2);
}
- (BOOL)my_hasPrefix:(id)str {
    NSLog(@"my_hasPrefix:%@",str);
    if(self && str && [self isKindOfClass:[NSString class]] && [self isKindOfClass:[NSString class]]) {
    NSRange range = [self rangeOfString:str];
    if( range.location!=NSNotFound&& range.location==0) {
        returnYES;
    }
    //或者使用 return [self my_hasPrefix:str]; 已交换过方法,此时会调用系统方法 hasPrefix:
}
  returnNO;
}
@end

运行:
NSString* str = @"test"
[str hasPrefix:nil];
或:((void(*)(id,SEL,NSString*))objc_msgSend)((id)str,@selector(hasPrefix:),nil);
程序再也不崩溃了 'NSInvalidArgumentException', reason: '-[__NSCFString hasPrefix:]: nil argument'

输出:2017-06-01 23:28:04.620919 NilArgsDemo[23957:7442610] my_hasPrefix:(null)

@END

你可能感兴趣的:(runtime 方法交换)