Reputation: 1
my code:
public protocol ApiRequestBaseObjProtocol {
var param:[String:Any] { get set }
var path:String {get}
}
extension ApiRequestBaseObjProtocol {
var param: [String : Any] {
get {
var key = "\(self.path)"
return (objc_getAssociatedObject(self, &key) as? [String : Any]) ?? [:]
}
set(newValue) {
var key = "\(self.path)"
objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
enum MeApi : ApiRequestBaseObjProtocol {
public var path: String {
return "test/api/xxx"
}
}
at param get{} method : objc_getAssociatedObject(self, &key) aways be nil. I want to know why? thank you!!
Upvotes: 0
Views: 349
Reputation: 4011
You are creating two separate keys so your &key
points to two separate things in getter and setter..
Try creating your key
as a static constant.
Per NSHipster:
It is often recommended that they key be a static char—or better yet, the pointer to one. Basically, an arbitrary value that is guaranteed to be constant, unique, and scoped for use within getters and setters:
Upvotes: 1