我在Swift中编写容器类,它在Java中与java.util.WeakHashMap
类似。我目前的实施就在这里。
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 }
}
在此实现中,容器中的holded对象通过WeakBox
被弱引用,因此保持值永远不会阻止对象在不再需要时被释放。
但显然这段代码存在问题;即使在其条目的对象被释放后,条目仍然存在。
要解决这个问题,我需要在释放一个holded对象之前挂钩,并删除它的(相应的)条目。我只知道NSObject
的解决方案,但它不适用于AnyObject
。
有人能帮帮我吗?谢谢。 (^ _ ^)
答案 0 :(得分:1)
不幸的是,didSet
或willSet
当{1} {}属性值被释放观察者不会被调用。
因此,在这种情况下你必须使用weak var raw
:
objc_setAssociatedObject
注意:在Swift 1.2之前。此解决方案不适用于任意Swift类。
答案 1 :(得分:1)
上一个示例有一些错误,例如:
字典错误的大小无效:此示例打印&#34; 1&#34;而不是&#34; 2&#34;:
let dict = WeakRefMap<String, NSObject>()
autoreleasepool {
let val = NSObject()
dict["1"] = val
dict["2"] = val
print("dict size: \(dict.count)")
}
修正了WeakRefMap:
private class DeallocWatcher<Key: Hashable> {
let notify:(keys: Set<Key>)->Void
private var keys = Set<Key>()
func insertKey(key: Key) {
keys.insert(key)
}
init(_ notify:(keys: Set<Key>)->Void) { self.notify = notify }
deinit { notify(keys: keys) }
}
public class WeakRefMap<Key: Hashable, Value: AnyObject> {
private var mapping = [Key: WeakBox<Value>]()
public init() {}
public subscript(key: Key) -> Value? {
get { return mapping[key]?.raw }
set {
if let o = newValue {
// Add helper to associated objects.
// When `o` is deallocated, `watcher` is also deallocated.
// So, `watcher.deinit()` will get called.
if let watcher = objc_getAssociatedObject(o, unsafeAddressOf(self)) as? DeallocWatcher<Key> {
watcher.insertKey(key)
} else {
let watcher = DeallocWatcher { [unowned self] (keys: Set<Key>) -> Void in
for key in keys {
self.mapping[key] = nil
}
}
watcher.insertKey(key)
objc_setAssociatedObject(o, unsafeAddressOf(self), watcher, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
mapping[key] = WeakBox(o)
} else {
if let index = mapping.indexForKey(key) {
let (_, value) = mapping[index]
objc_setAssociatedObject(value.raw, unsafeAddressOf(self), nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
mapping.removeAtIndex(index)
}
}
}
}
public var count: Int { return mapping.count }
deinit {
// cleanup
for e in self.mapping.values {
objc_setAssociatedObject(e.raw, unsafeAddressOf(self), nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}