美文网首页
runtime(交换方法)

runtime(交换方法)

作者: 陈水寒 | 来源:发表于2018-02-28 11:23 被阅读13次

需求:
比如说有一个项目,已经开发了2年,忽然项目负责人添加一个功能,每次UIImage加载图片,告诉我时候加载成功
可以采用的方法:

  1. 自定义UIImage
  2. UIImage添加分类
    弊端:1.每次使用,需要导入 2.项目大了,没办法实现,需要修改的地方太多

给系统的imageNamed添加功能,只能使用runtime(交换方法)

  1. 给系统的方法添加分类
  2. 自己实现一个带有扩展功能的方法
  3. 重写load方法,然后将方法进行交换,以UIImage类的 imageNamed方法为例
#import "UIImage+image.h"
#import <objc/message.h>

@implementation UIImage (image)

// 重写load方法,将系统方法与自定义方法进行交换
+ (void)load {
    Method imageNamed = class_getClassMethod(self, @selector(imageNamed:));
    Method gg_imageNamed = class_getClassMethod(self, @selector(gg_imageNamed:));
    
    method_exchangeImplementations(imageNamed, gg_imageNamed);
}

// 自定义一个扩展方法
+ (UIImage *)gg_imageNamed:(NSString *)name {
    UIImage *image = [UIImage gg_imageNamed:name];
    if (image) {
        NSLog(@"加载成功");
    }else {
        NSLog(@"加载失败");
    }
    
    return image;
    
}

@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/fakbxftx.html