5.上面的方法写了一个 OC 版本的:
.h:
#import
@interface UIViewController (FindLeaks)
// 默认为 NO
@property (nonatomic) BOOL noCheckLeaks;
@end
.m:
//
// UIViewController+FindLeaks.m
// Leaks
//
// Created by sunny on 2017/8/27.
// Copyright ? 2017年 CepheusSun. All rights reserved.
//
#import "UIViewController+FindLeaks.h"
#import
static const char *noCheckLeaksKey = "noChechLeaksKey";
@interface NSObject (MethodSwizzling)
+ (void)sy_swizzleInstanceSelector:(SEL)origSelector
swizzleSelector:(SEL)swizzleSelector;
@end
@implementation UIViewController (FindLeaks)
#pragma mark - Binding Property
- (BOOL)noCheckLeaks {
return [objc_getAssociatedObject(self, noCheckLeaksKey) boolValue];
}
- (void)setNoCheckLeaks:(BOOL)noCheckLeaks {
objc_setAssociatedObject(self, noCheckLeaksKey, [NSNumber numberWithBool:noCheckLeaks], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark - Check
+ (void)load {
#if DEBUG
[self sy_swizzleInstanceSelector:@selector(viewDidDisappear:) swizzleSelector:@selector(fl_viewDidDisappear:)];
#endif
}
- (void)fl_viewDidDisappear:(BOOL)animated {
[self fl_viewDidDisappear:animated];
if (!self.noCheckLeaks) {
[self fl_checkDeallocationAfterDelay:2];
}
}
- (void)fl_checkDeallocationAfterDelay:(NSTimeInterval)delay {
UIViewController *root = [self fl_rootParentViewController];
if (self.isMovingFromParentViewController || root.isBeingDismissed) {
NSString *type = NSStringFromClass([self class]);
NSString *disappearanceSource = self.isMovingFromParentViewController ? @"removed from its parent" : @"dismissed";
__weak typeof(self) weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSString *assert = [NSString stringWithFormat:@"%@ not deallocated after being %@",
type, disappearanceSource];
NSAssert(weakSelf == nil,assert);
});
}
}
- (UIViewController *)fl_rootParentViewController {
UIViewController *root = self;
while (root.parentViewController) {
root = root.parentViewController;
}
return root;
}
@end
@implementation NSObject (MethodSwizzling)
+ (void)sy_swizzleInstanceSelector:(SEL)origSelector
swizzleSelector:(SEL)swizzleSelector {
Method origMethod = class_getInstanceMethod(self, origSelector);
Method swizzleMethod = class_getInstanceMethod(self, swizzleSelector);
BOOL isAdd = class_addMethod(self, origSelector, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
if (!isAdd) {
method_exchangeImplementations(origMethod, swizzleMethod);
}else {
class_replaceMethod(self, swizzleSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
}
}
@end
只需要在不需要检查的方法中设置属性为 YES 就好了。