iOS 自定义一个简单的内存检测工具

原理: 给当前对象延迟发送消息 例如:当viewcontroller调用pop方法后它应该会被释放,此时在两秒后给它发送一个消息如果它还能响应则表示它未被正常释放.

1. 给UIViewController添加一个分类

在 + (void)load 通过methodswizzle 交换 viewWillAppear:(BOOL)animated 方法,并在新的方法里通过属性绑定添加一个标识默认为NO(如果为NO就不给它延迟发送消息,如果为YES则延迟发送消息).

Method appearMethod = class_getInstanceMethod([self class], @selector(viewWillAppear:));
    Method md_appearMethod = class_getInstanceMethod([self class], @selector(md_viewWillAppear:));
method_exchangeImplementations(appearMethod, md_appearMethod);

- (void)md_viewWillAppear:(BOOL)animated{
    [self md_viewWillAppear:animated];
    objc_setAssociatedObject(self, "md_mark", @(NO), 0);
}
2. 给UINavigationController添加一个分类

在 + (void)load 通过methodswizzle 交换 popViewControllerAnimated 方法,并在新的方法里, 将第一步添加的属性标识赋值为YES.

+ (void)load{
    Method popMethod = class_getInstanceMethod([self class], @selector(popViewControllerAnimated:));
    Method md_popMethod = class_getInstanceMethod([self class], @selector(md_popViewControllerAnimated:));
    method_exchangeImplementations(popMethod, md_popMethod);
}

- (UIViewController *)md_popViewControllerAnimated:(BOOL)animated{
    UIViewController *poppedController = [self md_popViewControllerAnimated:animated];
    objc_setAssociatedObject(poppedController, "md_mark", @(YES), 0);
    return poppedController;
}
3. 延迟发送消息

在第一步创建的分类里再通过methodswizzle 交换viewDidDisappear方法(或者viewWillDisappear也行)在新的方法里通过判断属性标识,再延迟发送消息(如果strongSelf为nil表示正常释放,否则表示存在内存泄漏).

+ (void)load{
   Method disappearMethod = class_getInstanceMethod([self class], @selector(viewDidDisappear:));
    Method md_disappearMethod = class_getInstanceMethod([self class], @selector(md_viewDidDisappear:));
 method_exchangeImplementations(disappearMethod, md_disappearMethod);
}
- (void)md_viewDidDisappear:(BOOL)animated{
    [self md_viewDidDisappear:animated];
    BOOL md_mark = [objc_getAssociatedObject(self, "md_mark") boolValue];
    if (md_mark) {
        __weak typeof(self)weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            __strong typeof(self)strongSelf = weakSelf;
            if (strongSelf) {
                NSLog(@":%@",strongSelf);
            }else{
               // NSLog(@"ok!!!!!");
            }
        });
    }
}
4. 这时候就可以测试了

在ViewController2里故意写一个block循环引用

 self.block = ^{
        self.index = 5;
    };

在pop回去2秒后,控制台会打印未释放的控制器:

2019-07-09 15:57:46.930865+0800 NeiCun[4928:154041] :

你可能感兴趣的:(iOS 自定义一个简单的内存检测工具)