在iOS的runtime中有交换方法名的函数,称为swizzle,以下示例将imageWithName:与imageNamed:两个方法进行了交换,这样调用系统方法imageNamed:实际调用的是imageWithName:,所有图片名称都拼接_os7,当旧项目需要更改一套图片时可以免去一个个更改。
@implementation UIImage (Extension)
/**
* 只要分类被装载到内存中,就会调用1次
*/
+ (void)load
{
Method otherMehtod = class_getClassMethod(self, @selector(imageWithName:));
Method originMehtod = class_getClassMethod(self, @selector(imageNamed:));
// 交换2个方法的实现
method_exchangeImplementations(otherMehtod, originMehtod);
}
+ (UIImage *)imageWithName:(NSString *)name
{
BOOL iOS7 = [[UIDevice currentDevice].systemVersion floatValue] >= 7.0;
UIImage *image = nil;
if (iOS7) {
NSString *newName = [name stringByAppendingString:@"_os7"];
image = [UIImage imageWithName:newName];//这里实际调用的时系统方法imageNamed:
}
if (image == nil) {
image = [UIImage imageWithName:name];
}
return image;
}
@end