How to observe object deinit in Swift

Issue #70

  • Today I was browsing through Suas-iOS and the subscription links to life cycle of another object
1
subscription.linkLifeCycleTo(object: self)

It observes the deinit of another job, interesting approach 👍 , take a look in https://github.com/zendesk/Suas-iOS/blob/master/Sources/StoreDeinitCallback.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var deinitCallbackKey = "DEINITCALLBACK_SUAS"

// MARK: Registartion
extension Suas {

static func onObjectDeinit(forObject object: NSObject,
callbackId: String,
callback: @escaping () -> ()) {
let rem = deinitCallback(forObject: object)
rem.callbacks.append(callback)
}

static fileprivate func deinitCallback(forObject object: NSObject) -> DeinitCallback {
if let deinitCallback = objc_getAssociatedObject(object, &deinitCallbackKey) as? DeinitCallback {
return deinitCallback
} else {
let rem = DeinitCallback()
objc_setAssociatedObject(object, &deinitCallbackKey, rem, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return rem
}
}
}

@objc fileprivate class DeinitCallback: NSObject {
var callbacks: [() -> ()] = []

deinit {
callbacks.forEach({ $0() })
}
}

Comments