runtime真的超级好用

前几天产品提出新需求,大致就是需要把这个项目所有关于图片加载的状态告诉用户提高用户体验,听到这里就觉得大事不妙了,毕竟是两年多的项目,改起来不难但是会很麻烦。之前有看过runtime的文档所以就谢了个demo试下,结果几分钟改完,测试完全ok。今天分享下代码,很简单老鸟勿喷。

因为runtime有一个交换方法的API我们借助这个API就实现了。首先我们先在分类自定义一个我们自己的方法(+ (instancetype)imageWithName:(NSString *)name),有人会喷为什么不在分类里直接重写(因为会把系统的功能给覆盖掉,而且分类中不能调用super.)

+ (void)load
{
    
    Method imageWithName = class_getClassMethod(self, @selector(imageWithName:));
    
    Method imageName = class_getClassMethod(self, @selector(imageNamed:));
    
    method_exchangeImplementations(imageWithName, imageName);
    
    
}


+ (instancetype)imageWithName:(NSString *)name
{
   
    UIImage *image = [self imageWithName:name];
    
    if (image == nil) {
        NSLog(@"状态信息打印");
    }
    
    return image;
}
简简单单几行代码就把系统的imageNamed:方法替换成我们的imageWithName:name靠谱的可以试下



posted on 2017-02-15 10:44  wangdan_whut  阅读(132)  评论(0编辑  收藏  举报