美文网首页iOS DeveloperiOS 开发
ios拓展24-runtime交换方法

ios拓展24-runtime交换方法

作者: Abler | 来源:发表于2016-08-23 16:20 被阅读53次

runtime交换方法,这里以UIImage的 imageNamed 方法为例, 创建UIImage分类

  • 1.在load方法中设置 交换方法(在分类重写)
+ (void)load {// 加载分类的时候调用,不导入头文件,也会交换 
    // 获取原始的方法
    Method originMethod = class_getClassMethod([UIImage class], @selector(imageNamed:));
    // 获取新的方法
    Method newMethod = class_getClassMethod([UIImage class], @selector(customImageNamed:));
    // 交换方法
    method_exchangeImplementations(originMethod, newMethod);
}

// 获取对象方法
//class_getInstanceMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>)
// 获取类方法
//class_getClassMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>)
  • 2.实现customImageNamed方法
+ (UIImage *)customImageNamed:(NSString *)name {  
    NSString *skinFolderPath = [NSString stringWithFormat:@"%@",[NSBundle mainBundle].resourcePath];

    NSString *path = nil;
    if([name hasSuffix:@".png"]) {
        path = [NSString stringWithFormat:@"%@/%@",skinFolderPath,name];
    } else {
        path = [NSString stringWithFormat:@"%@/%@.png",skinFolderPath,name];
    }
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    if(image == nil) {
/*==================================*/
// 由于方法交换了,这里不能用  image =[UIImage imageNamed:name];
/*==================================*/
        image = [UIImage customImageNamed:name];
    }
    return image;
}
  • 3.此时调用 会走customImageNamed
self.imageView.image = [UIImage imageNamed:@"name"];

相关文章

网友评论

    本文标题:ios拓展24-runtime交换方法

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