instanceManagerFinalizerTemplate function
Template for an object that tracks when an object is deallocated.
Implementation
String instanceManagerFinalizerTemplate(SwiftOptions options) => '''
// Attaches to an object to receive a callback when the object is deallocated.
internal final class ${_instanceManagerFinalizerName(options)} {
private static let associatedObjectKey = malloc(1)!
private let identifier: Int64
// Reference to the delegate is weak because the callback should be ignored if the
// `InstanceManager` is deallocated.
private weak var delegate: ${instanceManagerFinalizerDelegateName(options)}?
private init(identifier: Int64, delegate: ${instanceManagerFinalizerDelegateName(options)}) {
self.identifier = identifier
self.delegate = delegate
}
internal static func attach(
to instance: AnyObject, identifier: Int64, delegate: ${instanceManagerFinalizerDelegateName(options)}
) {
let finalizer = ${_instanceManagerFinalizerName(options)}(identifier: identifier, delegate: delegate)
objc_setAssociatedObject(instance, associatedObjectKey, finalizer, .OBJC_ASSOCIATION_RETAIN)
}
static func detach(from instance: AnyObject) {
objc_setAssociatedObject(instance, associatedObjectKey, nil, .OBJC_ASSOCIATION_ASSIGN)
}
deinit {
delegate?.onDeinit(identifier: identifier)
}
}
''';