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 就好了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值