runtime中Method Swizzling的初步使用

刚接触到这个感觉比较有意思,不过过于依赖runtime的方法去修改方法实现是一个比较危险的行为,确实是用共同基类的方式来重写方法比较安全。只应当在确实需要的情况使用这种黑魔法。

#import "JWView.h"
#import 
@implementation JWView //继承自UIView
+ (void)load { //load方法是所有继承NSObject类都拥有的类方法,可以直接理解为这个方法加载的灰常早灰常的早!!
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        
        SEL originalSelector = @selector(willMoveToSuperview:); //View被加到父View的时候的回调
        SEL swizzledSelector = @selector(JWwillMoveToSuperview:);
        
        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);
        }
    });
}

- (void)JWwillMoveToSuperview:(UIView *)newSuperView {
    [self JWwillMoveToSuperview:newSuperView];
    //在这里写想要替换的内容
    NSLog(@"换方法成功");
}
@end

你可能感兴趣的:(runtime中Method Swizzling的初步使用)