自定内存监控

引言

1.我们开发中常常不经意间会引起内存不释放的问题,常见的self->block,block->self.property;Timer没有释放等循环引用问题,使得ViewController一直被引用而没有被释放,则不会实行dealloc/deinit。
2.如果不每个VC都去重写dealloc/deinit方法去显示地去打印或者使用Leaks工具等,开发者是不会那么容易发现得了内存健康出了状况的。
3.那我们可以紧紧抓住一个点:VC在pop/dismiss的时候,dealloc/deinit有没有调用。再进一步说,是pop/dismiss出去的那个控制器是否还打印出内存。

核心思想

1.给nil对象发送消息是不会崩溃的
2.查看pop/dismiss出去的那个控制器是否还有内存

分析怎么做

我们需要动态添加关联bool类型的属性,这个关联属性有什么用?记录当前VC在viewWillAppear和pop/dismiss时候的状态,在viewWillDisappear的时候延时检测VC这个对象有没有内存地址。这里为什么要延时?因为pop释放VC的内存需要一丢丢时间。那么剩下的操作就是hook系统方法。

实操

1.hook住NavigationController的popViewController(animated:)。用来做啥呢?插入代码:插入动态关联属性,给要pop出去的VC更改关联属性状态,true表示准备释放这个VC。

import UIKit

private let onceToken = "BaseNavigationController Method Swizzling"

class BaseNavigationController: UINavigationController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

extension BaseNavigationController {
    // 系统的initialize已经禁用,我们自己写一个,在AppDelegate的didFinishLaunchingWithOptions调用
    public class func initializeMethod() {
        if self != BaseNavigationController.self { return }
        DispatchQueue.once(token: onceToken) {
            let originalSelector = #selector(popViewController(animated:))
            let swizzlingSelector = #selector(swizzling_popViewController(animated:))
            // 封装好方法交换
            MethodSwizzlingTool.swizzling(cls: self, originalSelector: originalSelector, swizzledSelector: swizzlingSelector)
        }
        
    }
    
    @objc func swizzling_popViewController(animated: Bool) -> UIViewController? {
        // 插入动态关联属性
        let popVC = self.swizzling_popViewController(animated: animated)
        if let vc = popVC {
            // 给要pop出去的VC更改关联属性状态,true表示准备释放这个VC
            objc_setAssociatedObject(vc, &AssociatedKeys.ViewContorllerWillDeinit, true, .OBJC_ASSOCIATION_ASSIGN)
        }
        return popVC
    }
}

2.1 hook住ViewController的dismiss(animated:completion:)。插入代码:动态关联属性,给要dismiss出去的VC更改关联属性状态,true表示准备释放这个VC。
2.2 hook住ViewController的viewWillAppear(:)。插入代码:动态关联属性,给要dismiss出去的VC更改关联属性状态,false表示VC的表示view才将要显示了。
2.3 重头戏:hook住ViewController的viewWillDisappear(
:)。插入代码:得到关联属性的状态,如果是true,表示视图要消失即将回收VC的资源,这个时候才是关键!!给self发送对象看它是否响应,若响应了,说明没有释放内存。

private let onceToken = "BaseViewController Method Swizzling"

class BaseViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

extension BaseViewController {
    public class func initializeMethod() {
        if self != BaseViewController.self { return }
        // DispatchQueue函数保证代码只被执行一次,防止又被交换回去导致得不到想要的效果
        DispatchQueue.once(token: onceToken) {
            // 交换viewWillAppear
            let originalSelector = #selector(BaseViewController.viewWillAppear(_:))
            let swizzledSelector = #selector(BaseViewController.swizzled_viewWillAppear(animated:))
            MethodSwizzlingTool.swizzling(cls: self, originalSelector: originalSelector, swizzledSelector: swizzledSelector)
            // 交换viewWillDisappear
            let originalSelector1 = #selector(BaseViewController.viewWillDisappear(_:))
            let swizzledSelector1 = #selector(BaseViewController.swizzled_viewWillDisappear(animated:))
            MethodSwizzlingTool.swizzling(cls: self, originalSelector: originalSelector1, swizzledSelector: swizzledSelector1)
            // 交换dissmiss
            let originalSelector2 = #selector(BaseViewController.dismiss(animated:completion:))
            let swizzledSelector2 = #selector(BaseViewController.swizzlied_dismiss(animated:completion:))
            MethodSwizzlingTool.swizzling(cls: self, originalSelector: originalSelector2, swizzledSelector: swizzledSelector2)
        }
    }
}

extension BaseViewController {
  @objc func swizzled_viewWillAppear(animated: Bool) {
        self.swizzled_viewWillAppear(animated: animated)
        // 更改关联属性状态设置false,表示view才将要显示了
        objc_setAssociatedObject(self, &AssociatedKeys.ViewContorllerWillDeinit, false, .OBJC_ASSOCIATION_ASSIGN)
    }

    @objc func swizzled_viewWillDisappear(animated: Bool) {
        self.swizzled_viewWillDisappear(animated: animated)
        // 得到关联属性的状态,如果是true,表示视图要消失即将回收VC的资源,这个时候才是关键!!给self发送对象看它是否响应,若响应了,说明没有释放内存
        guard let state = objc_getAssociatedObject(self, &AssociatedKeys.ViewContorllerWillDeinit) as? Bool else { return }
        if state {
            // 核心在这!
            willDeinit()
        }
    }
    
    @objc func swizzlied_dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
        self.swizzlied_dismiss(animated: flag, completion: completion)
        // 给要dimiss出去的VC更改关联属性状态,true表示准备释放这个VC
        objc_setAssociatedObject(self, &AssociatedKeys.ViewContorllerWillDeinit, true, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
    }
}

3.查看pop/dismiss出去的那个控制器是否还有内存

extension BaseViewController {
  private func willDeinit() {
        /* 核心思想:
            1.给nil对象发送消息是不会崩溃的
            2.查看pop出去的那个控制器是否还有内存,如果是,则没有被释放
         */
        
        // ps:这里的延时是因为popViewController执行还是需要一定的时间
        DispatchQueue.main.asyncAfter(deadline: .now()+2.0) { [weak self] in
            // 如果self被释放了,给nil发送消息是不会响应的
            self?.isNotDeinit()
        }
    }
    
    private func isNotDeinit() {
        // 打印VC内存 - 这里可以弹框啥的给开发者做提示
        print(String.init(format: "%p is not deinit", self))
    }
}

4.在application的didFinishLaunchingWithOptions调用两个initializeMethod

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Hook: viewWillAppear/viewWillDisappear/dismiss
        BaseViewController.initializeMethod()
        // Hook: popViewController
        BaseNavigationController.initializeMethod()
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = .white
        window?.rootViewController = BaseNavigationController(rootViewController: ViewController())
        window?.makeKeyAndVisible()
        return true
    }

5.ViewController去push/present一个FirstViewController,在FirstViewController里面实现一个循环引用

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .red
    }
    
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        navigationController?.pushViewController(FirstViewController(), animated: true)
//        present(FirstViewController(), animated: true, completion: nil)
    }
}
class FirstViewController: BaseViewController {
    var str = "aaa"
    var callBack: (()->())?

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .blue
        // 实现一个有循环引用问题的block
        self.callBack = {
            DispatchQueue.main.asyncAfter(deadline: .now()+2.0, execute: {
                print(self.str)
            })
        }
        callBack?()
    }
 
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        navigationController?.popViewController(animated: true)
//        dismiss(animated: true, completion: nil)
    }
    
    deinit {
        // deinit不会执行,因为block造成循环引用了
        print("FirstViewController deinit")
    }
}

运行模拟器跑起来:
和我们预期结果一样,FirstViewController对象没有释放


自定内存监控_第1张图片
BC8AF9EC-58F8-4A53-ACF4-378E3E62A69D.png

代码地址

你可能感兴趣的:(自定内存监控)