我有自定义类,我想扩展它并添加存储的属性,我发现的解决方案之一是使用关联对象。我的代码如下所示:
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之类的标准项目时,它可以正常工作。
它仅适用于类(不适用于结构),仅适用于与objc兼容的类。
有关解决方法,另请参见:https : //wezzard.com/2015/10/09/associated-object-and-swift-struct/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句