gpt4 book ai didi

swift - 实现 KVO 投诉属性的协议(protocol)扩展

转载 作者:行者123 更新时间:2023-12-05 07:51:12 25 4
gpt4 key购买 nike

public class EntityA: NSManagedObject {
@NSManaged public private(set) var identifier: String
@NSManaged public private(set) var name: String
}

public class EntityB: NSManagedObject {
@NSManaged public private(set) var identifier: String
@NSManaged public private(set) var name: String
}

protocol NodeRepresentable {
var children: NSArray { get }
static var childrenKeyPaths: [String] { get }
}


extension NodeRepresentable where Self: NSManagedObject {
var children: NSArray { //swift compiler doesn't see this as KVC complaint
return Self.childrenKeyPaths.flatMap { keyPath in
return self.mutableSetValueForKey(keyPath)
}
}
}

extension EntityA: NodeRepresentable {
static var childrenKeyPaths: [String] {
return ["events", "groups", "races"]
}

var _children: NSArray { //this is KVC complaint
return self.children
}
}

extension EntityB: NodeRepresentable {

static var childrenKeyPaths: [String] {
return ["events", "groups", "markets"]
}

var _children: NSArray { //this is KVC complaint
return self.children
}
}

编译器找不到 EntityA 和 EntityB 上子项的 valueForKey。协议(protocol)扩展似乎没有实现 KVO 投诉属性。我试过在协议(protocol)上声明动态属性,但这不起作用。

是否有可能避免使用某种类型的语言功能在每个实体上声明计算变量?

最佳答案

Swift 属性扩展对 Objective-C 不可见。

尝试将 @objc 添加到声明中。即 @objc var children: ...

另见 https://developer.apple.com/forums/thread/122181

关于swift - 实现 KVO 投诉属性的协议(protocol)扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35222857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com