1.添加分类、利用Runtime方法交换实现实时监控某个ViewController
//
// UIViewController+Swizzling.m
#import "UIViewController+Swizzling.h"
#import @implementation UIViewController (Swizzling)
+ (void)load {
//我们只有在开发的时候才需要查看哪个viewController将出现
//所以在release模式下就没必要进行方法的交换
#ifdef DEBUG
//原本的viewWillAppear方法
Method viewWillAppear = class_getInstanceMethod(self, @selector(viewWillAppear:));
//需要替换成 能够输出日志的viewWillAppear
Method logViewWillAppear = class_getInstanceMethod(self, @selector(logViewWillAppear:));
//两方法进行交换
method_exchangeImplementations(viewWillAppear, logViewWillAppear);
#endif
}
- (void)logViewWillAppear:(BOOL)animated {
NSString *className = NSStringFromClass([self class]);
//在这里,你可以进行过滤操作,指定哪些viewController需要打印,哪些不需要打印
if ([className hasPrefix:@"UI"] == NO) {
NSLog(@"%@ will appear",className);
}
//下面方法的调用,其实是调用viewWillAppear
[self logViewWillAppear:animated];
}
@end
2.添加分类、利用Runtime快速定位到不能释放的Viewcontroller
#import "UIViewController+Extension.h"
#import <objc/runtime.h>
@implementation UIViewController (Extension)
#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];
}
3.给每个viewController添加属性
@property (copy, nonatomic) NSString *method;
static char MethodKey;
- (void)setMethod:(NSString *)method
{
objc_setAssociatedObject(self, &MethodKey, method, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)method
{
return objc_getAssociatedObject(self, &MethodKey);
}