I'm writing a container class in Swift, which works like as java.util.WeakHashMap
in Java. My current implementation is here.
class WeakRefMap<Key: Hashable, Value: AnyObject> {
private var mapping = [Key: WeakBox<Value>]()
subscript(key: Key) -> Value? {
get { return mapping[key]?.raw }
set {
if let o = newValue {
mapping[key] = WeakBox(o)
}
else {
mapping.removeValueForKey(key)
}
}
}
var count: Int { return mapping.count }
}
class WeakBox<E: AnyObject> {
weak var raw: E!
init( _ raw: E) { self.raw = raw }
}
In this implementation, holded objects in the container are weakly-referenced via WeakBox
, so holding values never prevents the objects from being released when not needed anymore.
But clearly there is a problem in this code; The entries remains even after the object of its entry is freed.
To solve this problem, I need to hook just before a holded object is released, and remove its (corresponding) entry. I know a solution only for NSObject
, but it's not applicable to AnyObject
.
Could anyone help me? Thanks. (^_^)