0

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!!

1 Answers1

1

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:

juhan_h
  • 3,965
  • 4
  • 29
  • 35
  • thank you first. now ,I understand what you mean. First of all, I found that I have two problems with this question. One is that the key is not 'static var' type, and the second is that enum is seems can't use AssociationManager. But I still want to ask, because the path is uncertain, so I can't use a fixed 'static var' type, is there a way to do what I want to achieve? – ShayneFCF Jun 30 '20 at 09:00
  • 1
    You can't really have dynamic keys (as far as I know). So trying to tie a `key` of an associated value to a dynamic variable will not work. However you could have a single `private let key = "myKey"` in this file and store a `Dictionary` that will have `path` as keys and your `[String: Any]` as value. – juhan_h Jun 30 '20 at 09:05
  • think you, I do it like you said. – ShayneFCF Jul 14 '20 at 06:47