iOS运行时--替换方法

如果你想修改现有类的一些方法时,可以使用OC的运行时特性,去替换想要修改的方法。

这里使用NSURL类做示例:

在模拟器中运行下面一段代码:

NSURL *url = [NSURL URLWithString:@"http://www.baidu.com/人民币"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSLog(@"request%@",request);

结果:

2018-07-17 14:34:49.819338+0800 test[48600:9501401] request<NSURLRequest: 0x604000018cf0> { URL: (null) }

URL为空,这是因为urlstring中包含中文,需要编译,如果你在多处使用了NSURL方法,修改的话你需要去多处修改,如果使用替换方法,只需要在分类中修改就可以了


#import "NSURL+HMCNSURL.h"
#import <objc/message.h>

@implementation NSURL (HMCNSURL)

//在加载的时候会调用此方法
+ (void)load{
    Method method1 = class_getClassMethod([NSURL class], @selector(HMCURLWithString:));
    Method method2 = class_getClassMethod([NSURL class], @selector(URLWithString:));
    method_exchangeImplementations(method1, method2);
}

+ (instancetype)HMCURLWithString:(NSString *)URLString{
    URLString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //这里一定要使用HMCURLWithString方法,不能使用URLWithString方法,因为会造成死循环
    NSURL *url = [NSURL HMCURLWithString:URLString];
    if(url==nil){
        NSLog(@"url为空!");
    }
    return url;
}

@end

结果如下:

2018-07-17 17:30:30.701098+0800 test[50869:9753758] request<NSURLRequest: 0x60800001fc50> { URL: http://www.baidu.com/%E4%BA%BA%E6%B0%91%E5%B8%81 }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值