我正在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 }
}
在这个实现中,容器中保留的对象通过WeakBox
被弱引用,因此保留值永远不会阻止对象在不再需要时被释放。
但很明显,这段代码存在问题;即使在其条目的对象被释放之后,条目仍然保留。
为了解决这个问题,我需要在一个被扣留的对象被释放之前挂起,并移除它的(对应的)条目。我只知道NSObject
的解决方案,但它不适用于AnyObject
。
有人能帮我吗?谢谢(^_^)
遗憾的是,当weak var raw
属性值被释放时,didSet
或willSet
观察器不会被调用。
因此,在这种情况下,您必须使用objc_setAssociatedObject
:
// helper class to notify deallocation
class DeallocWatcher {
let notify:()->Void
init(_ notify:()->Void) { self.notify = notify }
deinit { notify() }
}
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 {
// Add helper to associated objects.
// When `o` is deallocated, `watcher` is also deallocated.
// So, `watcher.deinit()` will get called.
let watcher = DeallocWatcher { [unowned self] in self.mapping[key] = nil }
objc_setAssociatedObject(o, unsafeAddressOf(self), watcher, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
mapping[key] = WeakBox(o)
}
else {
mapping[key] = nil
}
}
}
var count: Int { return mapping.count }
deinit {
// cleanup
for e in self.mapping.values {
objc_setAssociatedObject(e.raw, unsafeAddressOf(self), nil, 0)
}
}
}
注意:Swift 1.2之前。此解决方案不适用于任意Swift类
上一个例子有一些错误,例如:
字典错误的大小无效:此示例打印"1"而不是"2":
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)
}
}
}