Swift 无法设置扩展中具有关联对象的存储属性

Swift 无法设置扩展中具有关联对象的存储属性,swift,objective-c-runtime,associated-object,Swift,Objective C Runtime,Associated Object,我有一个自定义类,我想扩展它并添加存储属性,我找到的解决方案之一就是使用关联对象来实现它。我的代码如下所示: import ObjectiveC var kSomeKey = "s" extension ProductCategory { var parent: ProductCategory? { get { return objc_getAssociatedObject(self, &kSomeKey) as? ProductCat

我有一个自定义类,我想扩展它并添加存储属性,我找到的解决方案之一就是使用关联对象来实现它。我的代码如下所示:

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)
        }
    }
}
我将此属性设置为:

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)
        }
    }
}
在debug中,我总是得到nil,但在set方法中,newValue被正确地接收。 请你提个建议,这个问题在哪里


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

它仅适用于类(而不是结构),并且仅适用于那些与objc兼容的类


有关解决方法,请参见:

ProductCategory是@objC类还是从NSObject派生的?@Daij Djan它只是一个结构。我想我明白了。那么,是否可以使用关联对象来扩展结构?@daijdjan,非常感谢!!!我读了这篇文章,但没有支付扩展费,因为扩展是为一个类完成的