我尝试将字符串与UIViewController
相关联,并且代码无法关联" key"到UIViewController
private var key: Void?
objc_setAssociatedObject(self, &key, "key",.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
print(objc_getAssociatedObject(self, &key) as? String)
这里self是UIViewController
而key是无效的?
这是我发现的一个演示,密钥没有定义,但代码工作
class MyClass {
func printTitle(input: MyClass) {
if let title = input.title {
print("Title: \(title)")
} else {
print("nil")
}
}
}
// MyClassExtension.swift
private var key: Void?
extension MyClass {
var title: String? {
get {
return objc_getAssociatedObject(self, &key) as? String
}
set {
objc_setAssociatedObject(self,
&key, newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}