runtime交換方法,這里以UIImage的 imageNamed 方法為例, 創(chuàng)建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.實現(xiàn)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"];