ios 修复 内存泄露_iOS 内存泄漏如何解决
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 就好了。
總結
以上是生活随笔為你收集整理的ios 修复 内存泄露_iOS 内存泄漏如何解决的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sql 1行拆分成两行_EXCEL总表拆
- 下一篇: controller怎么调用contro