NSValue(nonretainedObject:)
不是指定的初始化程序。NSValue 引用中列出的唯一初始化程序(以及因此指定的初始化程序)是NSValue(value:CConstVoidPointer, withObjCType type:CString)
其他构造函数都是从类助手方法派生的便利构造函数。
你可以试试:
init(baseObject: T) {
super.init(bytes:&baseObject, withObjCType:"^v")
}
"^v" 是使用 valueWithNonRetained... 创建的 NSValue 返回的类型字符串。
Unfortunately, I'm not coming up with an appropriate way to pass baseObject
as a CConstVoidPointer.
Barring that, the best thing I can come up with is to wrap NSValue instead of subclassing it:
class ID<T:AnyObject> {
let wrapped:NSValue
init(baseObject:T) {
wrapped = NSValue(nonretainedObject:baseObject)
}
}
Finally got something to work, but it's a little bit ugly, basically add a convenience constructor that wraps the nonretainedObject constructor and then use that in your subclass:
extension NSValue {
convenience init<T:AnyObject>(unretained:T) {
self.init(nonretainedObject:unretained)
}
}
class ID<T>:NSValue {
convenience init<T:AnyObject>(unretained:T) {
self.init(unretained:unretained)
}
}
Depending on what you're actually trying to do the category alone might be sufficient?