美文网首页
runtime 方法交换

runtime 方法交换

作者: ganld | 来源:发表于2017-06-01 23:43 被阅读0次

为 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

    runtime交换方法 动态添加方法

  • runTime常用方法

    使用runTime改变实例成员的值 使用runtime来交换两个方法 注意再次调用该方法不交换 使用runTime...

  • Runtime

    runtime运行时机制1:通过runtime,实现方法交换(交换两个类方法、交换两个实例方法)2:通过runti...

  • Day3

    1 runtime运行时机制1:通过runtime,实现方法交换(交换两个类方法、交换两个实例方法)。2:通过ru...

  • runtime的理解(二)

    主要内容 利用 runtime 交换方法 利用 runtime 动态添加方法 利用 runtime 动态添加属性 ...

  • 查看SDK调用支付宝参数

    使用runtime 方法交换openurl

  • objc runtime (四)动态添加属性

    在《objc runtime (二)交换方法》中我提到过runtime最实用的就是交换方法和动态添加属性两个用法。...

  • iOS runtime如何交换两个类方法

    如有转载,请标明出处:iOS runtime如何交换两个类方法 runtime交换实例方法,老生常谈的问题,很多b...

  • iOS -- runtime的应用

    runtime主要有一下几种应用场景 方法交换 添加属性 (一)方法交换 (1)字体适配 方法交换实际交换的是方法...

  • runtime和oc内存区域(2018-04-02)

    runtime常用的几个方法: 交换方法 动态添加属性 动态添加方法 1.交换方法 class_getClassM...

网友评论

      本文标题:runtime 方法交换

      本文链接:https://www.haomeiwen.com/subject/nyryfxtx.html