0

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.

Melany
  • 466
  • 7
  • 20
  • 1
    is ProductCategory a @objC class or derived from NSObject? – Daij-Djan Feb 01 '17 at 13:25
  • @ Daij-Djan its just a struct. Well I suppose I get the issue. So is it possible to extend structs with the usage of assocciated objects? – Melany Feb 01 '17 at 13:38

1 Answers1

1

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/

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • @ Daij-Djan, thanks you very much!!! I read this article, but didn't pay extension that extension was done for a class – Melany Feb 01 '17 at 13:43