0

我有自定义类,我想扩展它并添加存储属性,我发现的解决方案之一是使用 Associated 对象。我的代码如下所示:

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")
        }
    }
}

我这样设置这个属性:

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

在调试中我总是得到 nil,但在 set 方法中,newValue 被正确接收。请问各位大神,这个问题出在哪里?

有趣的是,当将此方法应用于 UINavigationController 等标准项目时,它可以正常工作。

4

1 回答 1

1

它仅适用于类(而非结构),并且仅适用于与 objc 兼容的类。

有关解决方法,另请参阅:https ://wezzard.com/2015/10/09/associated-object-and-swift-struct/

于 2017-02-01T13:40:33.373 回答