我有自定义类,我想扩展它并添加存储属性,我发现的解决方案之一是使用 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 等标准项目时,它可以正常工作。