I try to associate a string to the UIViewController
,and the code fails to associate "key" to UIViewController
private var key: Void?
objc_setAssociatedObject(self, &key, "key",.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
print(objc_getAssociatedObject(self, &key) as? String)
here self is UIViewController
and key is a void?
This is a demo i found,the key is not defined,but the code works
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)
}
}
}