UIViewController+MemoryLeak.m 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * Tencent is pleased to support the open source community by making MLeaksFinder available.
  3. *
  4. * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
  5. *
  6. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
  7. *
  8. * https://opensource.org/licenses/BSD-3-Clause
  9. *
  10. * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
  11. */
  12. #import "UIViewController+MemoryLeak.h"
  13. #import "NSObject+MemoryLeak.h"
  14. #import <objc/runtime.h>
  15. #if _INTERNAL_MLF_ENABLED
  16. const void *const kHasBeenPoppedKey = &kHasBeenPoppedKey;
  17. @implementation UIViewController (MemoryLeak)
  18. + (void)load {
  19. static dispatch_once_t onceToken;
  20. dispatch_once(&onceToken, ^{
  21. [self swizzleSEL:@selector(viewDidDisappear:) withSEL:@selector(swizzled_viewDidDisappear:)];
  22. [self swizzleSEL:@selector(viewWillAppear:) withSEL:@selector(swizzled_viewWillAppear:)];
  23. [self swizzleSEL:@selector(dismissViewControllerAnimated:completion:) withSEL:@selector(swizzled_dismissViewControllerAnimated:completion:)];
  24. });
  25. }
  26. - (void)swizzled_viewDidDisappear:(BOOL)animated {
  27. [self swizzled_viewDidDisappear:animated];
  28. if ([objc_getAssociatedObject(self, kHasBeenPoppedKey) boolValue]) {
  29. [self willDealloc];
  30. }
  31. }
  32. - (void)swizzled_viewWillAppear:(BOOL)animated {
  33. [self swizzled_viewWillAppear:animated];
  34. objc_setAssociatedObject(self, kHasBeenPoppedKey, @(NO), OBJC_ASSOCIATION_RETAIN);
  35. }
  36. - (void)swizzled_dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion {
  37. [self swizzled_dismissViewControllerAnimated:flag completion:completion];
  38. UIViewController *dismissedViewController = self.presentedViewController;
  39. if (!dismissedViewController && self.presentingViewController) {
  40. dismissedViewController = self;
  41. }
  42. if (!dismissedViewController) return;
  43. [dismissedViewController willDealloc];
  44. }
  45. - (BOOL)willDealloc {
  46. if (![super willDealloc]) {
  47. return NO;
  48. }
  49. [self willReleaseChildren:self.childViewControllers];
  50. [self willReleaseChild:self.presentedViewController];
  51. if (self.isViewLoaded) {
  52. [self willReleaseChild:self.view];
  53. }
  54. return YES;
  55. }
  56. @end
  57. #endif