Runtime实现类方法的实现交换

场景:我们调用[UIImage imageNamed:@"1"]方法,但实现使用自定义的方法实现。

由于代码很简单,注释很详细,不做解释了,直接上代码。

#import <UIKit/UIKit.h>

@interface UIImage (Extension)

@end
#import "UIImage+Extension.h"
#import <objc/runtime.h> // 导入头文件

@implementation UIImage (Extension)

//当应用启动时,会对项目中所有的类进行一次加载,此时就会调用该方法
+ (void)load{
    // 获取系统方法
    Method systemM = class_getClassMethod([UIImage class], @selector(imageNamed:));
    // 获取自定义方法
    Method customM = class_getClassMethod([UIImage class], @selector(ysImageNamed:));
    // 运行时交换两个方法的实现:注意死循环问题
    method_exchangeImplementations(systemM, customM);
}

// 当该类被首次使用时调用
+ (void)initialize{
    
}

/**
 自定义类方法,用于和系统方法“实现”交换

 @param imgName 图片名称
 @return 图片
 */
+ (UIImage *)ysImageNamed:(NSString *)imgName{
    NSString *name = [NSString stringWithFormat:@"%@_white",imgName];
    // 注意:这里一定要调用自定义方法,不能调用imageNamed:方法,否则会引起死循环,因为此方法和imageNamed:的实现交换了
    return [UIImage ysImageNamed:name];
}

@end

 

posted @ 2017-02-06 10:13  小课桌  阅读(368)  评论(0编辑  收藏  举报