一、使用runtime实现查看 imageNamed:是否加载成功

最近学习runtime初读文档不是很了解,于是找到几个案例先熟悉一下用法

    1. 首先新建category
    2. 自定义方法
    3. 方法交换

使用runtime实现方法交换,首先需要倒入头文件#import

#import "UIImage+Image.h"
#import 

@implementation UIImage (Image)

+(void)load
{
    Method imageNamedMethod = class_getClassMethod(self, @selector(imageNamed:));
    Method jzg_imageMethod = class_getClassMethod(self, @selector(jzg_imageNamed:));
    method_exchangeImplementations(imageNamedMethod, jzg_imageMethod);
}

+ (UIImage *)jzg_imageNamed:(NSString *)name {
 
    //此处实际发送的消息是imageNamed:故而不会造成死循环
    UIImage *image = [UIImage jzg_imageNamed:name];
    if (image) {
        NSLog(@"图片加载成功");
    }else{
        NSLog(@"图片加载失败");
    }
    return image;
}

@end

实际调用

UIImageView *theImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"aaaaaa"]];
    [self.view addSubview:theImageView];
    [theImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(10, 10, 10, 10));
    }];

注:不能直接重写imageNamed:方法,因为category中不能调用父类方法,而你又不知道父类方法中具体的实现

你可能感兴趣的:(一、使用runtime实现查看 imageNamed:是否加载成功)