forked from Tencent/MLeaksFinder
/
UIViewController+MemoryLeak.m
84 lines (63 loc) · 2.58 KB
/
UIViewController+MemoryLeak.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//
// UIViewController+MemoryLeak.m
// MLeaksFinder
//
// Created by zeposhe on 12/12/15.
// Copyright © 2015 zeposhe. All rights reserved.
//
#import "UIViewController+MemoryLeak.h"
#import "NSObject+MemoryLeak.h"
#import <objc/runtime.h>
#ifdef DEBUG
const void *const kHasBeenPoppedKey = &kHasBeenPoppedKey;
@implementation UIViewController (MemoryLeak)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self swizzleSEL:@selector(viewDidDisappear:) withSEL:@selector(swizzled_viewDidDisappear:)];
[self swizzleSEL:@selector(viewWillAppear:) withSEL:@selector(swizzled_viewWillAppear:)];
[self swizzleSEL:@selector(dismissViewControllerAnimated:completion:) withSEL:@selector(swizzled_dismissViewControllerAnimated:completion:)];
});
}
- (void)swizzled_viewDidDisappear:(BOOL)animated {
[self swizzled_viewDidDisappear:animated];
if ([objc_getAssociatedObject(self, kHasBeenPoppedKey) boolValue]) {
[self willDealloc];
}
}
- (void)swizzled_viewWillAppear:(BOOL)animated {
[self swizzled_viewWillAppear:animated];
objc_setAssociatedObject(self, kHasBeenPoppedKey, @(NO), OBJC_ASSOCIATION_RETAIN);
}
- (void)swizzled_dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion {
[self swizzled_dismissViewControllerAnimated:flag completion:completion];
UIViewController *dismissedViewController = self.presentedViewController;
if (!dismissedViewController && self.presentingViewController) {
dismissedViewController = self;
}
if (!dismissedViewController) return;
[dismissedViewController willDealloc];
}
- (BOOL)willDealloc {
if (![super willDealloc]) {
return NO;
}
NSArray *viewStack = [self viewStack];
for (UIViewController *viewController in self.childViewControllers) {
NSString *className = NSStringFromClass([viewController class]);
[viewController setViewStack:[viewStack arrayByAddingObject:className]];
[viewController willDealloc];
}
UIViewController *presentedViewController = self.presentedViewController;
if (presentedViewController) {
NSString *className = NSStringFromClass([presentedViewController class]);
[presentedViewController setViewStack:[viewStack arrayByAddingObject:className]];
[presentedViewController willDealloc];
}
NSString *className = NSStringFromClass([self.view class]);
[self.view setViewStack:[viewStack arrayByAddingObject:className]];
[self.view willDealloc];
return YES;
}
@end
#endif