我正在尝试将自定义类用作NSDictionary中的键。为此,根据编译器,我需要实现NSCopying协议。我遵循this建议,但似乎无效。这是我的代码:
我的协议是我的密钥类所遵循的:
// My custom protocol
protocol TestProtocol: NSCopying {
func testFunc()
}
当我将NSCopying协议实现给类返回时,一切似乎都运行得很好:
// Custom key class
class KeyClass: NSObject, TestProtocol {
func testFunc() {
}
func copyWithZone(zone: NSZone) -> AnyObject {
return self
}
}
现在我正在调用代码:
let key = KeyClass()
let dictionary = NSMutableDictionary()
dictionary.setObject("TestString", forKey: key)
let value = dictionary[key]
值包含“TestString”
但当我从另一个堆栈主题改变KeyClass实现时:
class KeyClass: NSObject, TestProtocol {
func testFunc() {
}
required override init() {
}
required init(_ model: KeyClass) {
}
func copyWithZone(zone: NSZone) -> AnyObject {
return self.dynamicType.init(self)
}
}
我的价值变量一直是零。任何人都可以向我解释为什么上面的实现不起作用?
答案 0 :(得分:0)
我猜协议继承者不适用于OC对象。因此,请尝试像[KeyClass:String]
这样的快速字典,或者不要继承任何协议。