Search code examples
swiftobjective-c-runtimeassociated-object

cant set stored property with associated object in extention


I have custom class, and I want to extend it and add stored property, one of solutions I found is to do it with Associated objects. My Code looks like that:

import ObjectiveC

var kSomeKey = "s"

extension ProductCategory {
    var parent: ProductCategory? {
        get {
            return objc_getAssociatedObject(self, &kSomeKey) as? ProductCategory
        }
        set(newValue) {
            objc_setAssociatedObject(self, &kSomeKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            print(parent ?? "not set")
        }
    }
}

I make setting of this property like that:

 private func makeConnectionsWithParents(forArray sorce: ProductCategory) {
    for var cheesItem in sorce.childCategories! {
        if cheesItem.childCategories != nil {
           cheesItem.parent = sorce
            makeConnectionsWithParents(forArray: cheesItem)
        }
    }
}

in debug I always get nil, but in set method, the newValue is received properly. Could you, please , advice, where is the issue with this?

what is interesting, when apply this approach to standard items like UINavigationController, it works properly.


Solution

  • it only works right for classes (not structs) and on top only for those that are objc compatible.

    for a workaround, see also: https://wezzard.com/2015/10/09/associated-object-and-swift-struct/