简单使用runtime+UIViewController的分类在dealloc方法中添加打印信息

此方法copy自MJRefresh的demo

给UIViewController创建一个分类Category名Example

.h

#import 

@interface UIViewController (Example)

@end

.m

#import "UIViewController+Example.h"
#import 

@implementation UIViewController (Example)

#pragma mark - swizzle
+ (void)load
{
    Method method1 = class_getInstanceMethod([self class], NSSelectorFromString(@"dealloc"));
    Method method2 = class_getInstanceMethod([self class], @selector(deallocSwizzle));
    method_exchangeImplementations(method1, method2);
}

- (void)deallocSwizzle
{
    NSLog(@"%@被销毁了", self);
    
    [self deallocSwizzle];
}

这样,工程中所有继承与UIViewController的控制器都会自动打印出NSLog(@"%@被销毁了", self) 这句信息。

注意:

.m文件中 - (void)deallocSwizzle{ }中调用的[self deallocSwizzle];其实是调用的[self dealloc]; 因为在+ (void)load{} 方法中已经交换了dealloc和deallocSwizzle方法的实现。

千万别忘了在其中调用[self deallocSwizzle], 不然会有问题。(相当于调用原始的dealloc方法)

你可能感兴趣的:(简单使用runtime+UIViewController的分类在dealloc方法中添加打印信息)