runtime 交换UIImage imageNamed 方法

1.新建UIimage 分类show.
UIImage+Show.h

#import 

NS_ASSUME_NONNULL_BEGIN

@interface UIImage (Show)


@end

NS_ASSUME_NONNULL_END

UIImage+Show.m

#import "UIImage+Show.h"
#import 

@implementation UIImage (Show)

+ (void)load {
    NSString *className = NSStringFromClass(self.class);
    NSLog(@"classname %@", className);
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //要特别注意你替换的方法到底是哪个性质的方法
        // When swizzling a Instance method, use the following:
        //        Class class = [self class];
        
        // When swizzling a class method, use the following:
        Class class = object_getClass((id)self);
        
        SEL originalSelector = @selector(imageNamed:);
        SEL swizzledSelector = @selector(zdx_imagedNamed:);
        
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        
        BOOL didAddMethod =
        class_addMethod(class,
                        originalSelector,
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));
        
        if (didAddMethod) {
            class_replaceMethod(class,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

+(UIImage*)zdx_imagedNamed:(NSString *)name {
    NSMutableString *mutaleStr = name.mutableCopy;
    [mutaleStr appendString:@"_obj"];
    NSLog(@"拼接的字符串%@",mutaleStr);
    UIImage *image = [UIImage zdx_imagedNamed:mutaleStr];
    
    
    if (image) {
        NSLog(@"runtime 添加额外功能成功--加载成功");
    } else {
        NSLog(@"runtime 添加额外功能成功--加载失败");
    }
    return image;
}

@end

调用:

_imgView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:_imgView];
    _imgView.image = [UIImage imageNamed:@"testImg"];

控制器打印:

2019-04-22 10:56:44.665 TestSwizDemo[5999:117295] 拼接的字符串testImg_obj
2019-04-22 10:56:44.666 TestSwizDemo[5999:117295] runtime 添加额外功能成功--加载失败

你可能感兴趣的:(runtime 交换UIImage imageNamed 方法)