swift deinit 没运行,没有进,没跑原因

delegate 要用 weak var

protocol MyProtocol: class {
    func updateData()
}

class ViewController: UIViewController {
    
    weak var delegate: MyProtocol? //1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
    }
    
    deinit {
        print("ViewController deinit")
    }
}

NotificationCenter 里用weak self

NotificationCenter.default.addObserver(forName: NSNotification.Name("notificationName"), object: nil, queue:
OperationQueue.main) { [weak self] notification in //1
    guard let strongSelf = self else { return } //2
    
    strongSelf.updateTask()
    // Write your code and use strongSelf instead of self
}

块Closure里要用 [weak self]

class ViewController: UIViewController {
    
    var myClosure: (() -> ())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.myClosure = { [weak self] in
            guard let strongSelf = self else { return }
            // Write your code and use strongSelf instead of self
            print("weak self is: \(strongSelf)")
        }
    }
    
    deinit {
        print("ViewController deinit")
    }
}

controller里任何对象对他的引用都不要strong reference

class MyCustomView: UIView {
    
    weak var viewC: ViewController? //1
}

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let subView = MyCustomView()
        subView.viewC = self
        self.view.addSubview(subView)
    }
    
    deinit {
        print("ViewController deinit")
    }
}

参考

https://www.swiftdevcenter.com/reasons-for-deinit-is-not-getting-called-ios-swift/#:~:text=When%20you%20pop%20your%20ViewController,and%20we%20must%20fix%20this.

猜你喜欢

转载自blog.csdn.net/linzhiji/article/details/128788403