在Swift中(我正在使用4.1),有没有办法在对象被破坏时在扩展中做一些清理?我想到了deinit()
中的代码类型,但扩展名无法声明deinit()
。 (除此之外,如果需要执行多个扩展,则会有多个deinit()
声明。)
答案 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
DeinitializationObserver
来处理这类事情。但是,它比我在这里写的更复杂。相反,它们看起来像是在调动Lifetime
选择器。如果您有兴趣,可以查看内部 - https://github.com/ReactiveCocoa/ReactiveCocoa/blob/master/ReactiveCocoa/NSObject+Lifetime.swift