Runtime是在不得不用时才进行使用的,一般情况下最好不要使用。Runtime的交换方法一般用于替换系统自带的方法,比如处理数组越界问题、判断图片是否加载成功,等等。本帖的举例说明判断图片是否加载成功。
- ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
//image的图片是随意起的名字,不存在图片
UIImage *image = [UIImage imageNamed:@"1"];
//这张是存在的
UIImage *image2 = [UIImage imageNamed:@"RadioHead"];
}
- 这里我们要使用自定义方法对UIImage的-imageNamed:方法进行交换,我们需要创建一个UIImage的类别(Category)UIImage+Image
#import "UIImage+Image.h"
#import <objc/message.h>//这里用于引入Runtime
@implementation UIImage (Image)
+(void)load{
Method method1 = class_getClassMethod([UIImage class], @selector(imageNamed:));
Method method2 = class_getClassMethod([UIImage class], @selector(tw_imageNamed:));
method_exchangeImplementations(method1, method2);
}
//自定义方法
+(UIImage *)tw_imageNamed:(NSString *)name{
UIImage *image = [UIImage tw_imageNamed:name];
if (image) {
NSLog(@"加载图片成功: FUNCTION:%s;imageName:\"%@\"",__FUNCTION__,name);
}else{
NSLog(@"警告!加载图片失败:FUNCTION:%s;imageName:\"%@\"",__FUNCTION__,name);
}
return image;
}
@end
- 运行效果