在对象deinit上调用扩展中的代码?

时间:2018-04-13 18:17:49

标签: swift memory-leaks deinit

在Swift中(我正在使用4.1),有没有办法在对象被破坏时在扩展中做一些清理?我想到了deinit()中的代码类型,但扩展名无法声明deinit()。 (除此之外,如果需要执行多个扩展,则会有多个deinit()声明。)

1 个答案:

答案 0 :(得分:6)

我没有找到完全得到你想要的方法,但也许这段代码会有所帮助。我从来没有尝试过,所以也许更多地使用它作为灵感。简而言之,它允许您添加将在取消初始化时执行的代码。

/// This is a simple object whose job is to execute
/// some closure when it deinitializes
class DeinitializationObserver {

    let execute: () -> ()

    init(execute: @escaping () -> ()) {
        self.execute = execute
    }

    deinit {
        execute()
    }
}

/// We're using objc associated objects to have this `DeinitializationObserver`
/// stored inside the protocol extension
private struct AssociatedKeys {
    static var DeinitializationObserver = "DeinitializationObserver"
}

/// Protocol for any object that implements this logic
protocol ObservableDeinitialization: AnyObject {

    func onDeinit(_ execute: @escaping () -> ())

}

extension ObservableDeinitialization {

    /// This stores the `DeinitializationObserver`. It's fileprivate so you
    /// cannot interfere with this outside. Also we're using a strong retain
    /// which will ensure that the `DeinitializationObserver` is deinitialized
    /// at the same time as your object.
    fileprivate var deinitializationObserver: DeinitializationObserver {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.DeinitializationObserver) as! DeinitializationObserver
        }
        set {
            objc_setAssociatedObject(
                self,
                &AssociatedKeys.DeinitializationObserver,
                newValue,
                objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
            )    
        }
    }

    /// This is what you call to add a block that should execute on `deinit`
    func onDeinit(_ execute: @escaping () -> ()) {
        deinitializationObserver = DeinitializationObserver(execute: execute)
    }
}

如何运作

现在让我们假设你有了你的对象,我们称之为A并且你想在扩展中创建一些代码,你可以使用onDeinit来添加你的清理代码:

extension A {

    func someSetup() {

        // Do your thing...


        onDeinit {
            /// This will be executed when A is deinitialized
            print("Execute this")
        }
    }
}

您也可以从扩展程序外部添加

let a = A()
a.onDeinit {
    print("Deinitialized")
}

讨论

  • 这与您想要的不同,而不是定义您需要调用的函数(deinit)。但无论如何,在协议扩展中,你永远不能真正使用底层对象的生命周期,所以对大多数情况来说它应该没问题。
  • 我不确定A的{​​{1}}和deinit DeinitializationObserver之间的执行顺序。在封闭内部编写代码时,您可能需要放弃deinit仍在内存中的假设。
  • 如果您需要多个A,可以更新相关对象以保留onDeinit
  • 数组
  • 在我的代码中,我通常使用ReactiveCocoa的DeinitializationObserver来处理这类事情。但是,它比我在这里写的更复杂。相反,它们看起来像是在调动Lifetime选择器。如果您有兴趣,可以查看内部 - https://github.com/ReactiveCocoa/ReactiveCocoa/blob/master/ReactiveCocoa/NSObject+Lifetime.swift