本文是在控制器的基础上添加了一个 Category
,只需导入 Category
并引用头文件,不需要在项目里引用其他代码,就可以检测控制器是否被销毁。具体代码如下:
UIViewController+Example.h
//
// UIViewController+Example.h
//
// Created by TL on 2017/4/6.
// Copyright © 2017年 TL. All rights reserved.
//
#import "UIViewController.h"
@interface RootViewController (Example)
@property (copy, nonatomic) NSString *method;
@end
UIViewController+Example.m
//
// UIViewController+Example.m
//
// Created by TL on 2017/4/6.
// Copyright © 2017年 TL. All rights reserved.
//
#import "UIViewController+Example.h"
@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);
}
static char MethodKey;
- (void)setMethod:(NSString *)method
{
objc_setAssociatedObject(self, &MethodKey, method, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)method
{
return objc_getAssociatedObject(self, &MethodKey);
}
@end
没有一蹴而就的天才,只有不断点亮天赋的勤者