我有一个 ViewController,我使用关联对象向其中添加了两个新属性:一个枚举和一个字符串(字符串版本取自此处)
这是我的示例代码:
extension UIViewController {
private struct AssociatedKeys {
static var handle = "handle"
}
enum CustomStringEnum: String {
case One = "One"
case Two = "Two"
case Three = "Three"
}
var customEnum: CustomStringEnum {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.handle) as? CustomStringEnum ?? .One
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.handle, newValue.rawValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var descriptiveName: String {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.handle) as! String
}
set {
objc_setAssociatedObject(
self,
&AssociatedKeys.handle,
newValue as NSString?,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let vc = UIViewController()
vc.customEnum = .Three
vc.descriptiveName = "Three"
print(vc.customEnum.rawValue) // -> This prints "One"
print(vc.descriptiveName) // -> This prints "Three"
}
}
字符串版本可以正常工作,但枚举版本不能。而且我不确定问题是什么。
这是objc_getAssociatedObject
或 的问题objc_setAssociatedObject
。get版本好像一直都是nil,所以返回默认值One。