iOS Swizzled 方法的替换、给原方法修改、添加代码

在iOS的开发当中、我们需要对原有的方法进行改进时,我们可以通过重写父类实现。但是,当我们需要在所有的子类都要修改父类方法,如果父类是我们自定义的API当然可以直接修改API,通常需要修改系统API活着三方库,就需要用到runtime时机制进行方法替换活着补救。
本文章以hook原系统的dealloc方法添加一句NSLog来打印当前页面的释放状态

采用category重写 load 方法,导入工程即可实现方法的替换

UIViewController+Swizzled.h

//
//  UIViewController+Swizzled.h
//  FtxBookViaPhone
//
//  Created by Jone on 2017/2/13.
//  Copyright © 2017年 FTXJOY. All rights reserved.
//

#import 

@interface UIViewController (Swizzled)

@end

UIViewController+Swizzled.m

//
//  UIViewController+Swizzled.m
//  FtxBookViaPhone
//
//  Created by Jone on 2017/2/13.
//  Copyright © 2017年 FTXJOY. All rights reserved.
//

#import "UIViewController+Swizzled.h"

@implementation UIViewController (Swizzled)

+(void)load {
    [super load];
    
    __weak typeof(self) weakSelf = self;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [weakSelf class];
        Method oldMethod = class_getInstanceMethod(weakSelf, NSSelectorFromString(@"dealloc"));
        Method newMethod = class_getInstanceMethod(weakSelf, @selector(swizzledDealloc));
        BOOL didAddMethod = class_addMethod(class, NSSelectorFromString(@"dealloc"), method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
        if (didAddMethod) {
            class_replaceMethod(class, @selector(swizzledDealloc), method_getImplementation(oldMethod), method_getTypeEncoding(oldMethod));
        } else {
            method_exchangeImplementations(oldMethod, newMethod);
        }
    });
}

- (void)swizzledDealloc {
    NSLog(@"print:dealloc-%@",NSStringFromClass([self class]));
    
    [self swizzledDealloc];
}

@end

Demo

你可能感兴趣的:(iOS Swizzled 方法的替换、给原方法修改、添加代码)