【问题标题】:Function for custom setter / getter Core Data自定义设置器/获取器核心数据的功能
【发布时间】:2025-12-21 00:10:12
【问题描述】:

我正在尝试创建一个全局函数,以便我的核心数据类可以使用此函数来创建自定义设置器。但我得到了'willChangeValueForKey'的模棱两可的使用。

我使用的代码是:

func coredataSetter<T: NSManagedObject>(entity: T, attribute: CustomStringConvertible, value: String) {
    entity.willChangeValueForKey(attribute.description)
    entity.setPrimitiveValue(value, forKey: attribute.description)
    entity.didChangeValueForKey(attribute.description)
}

我有点迷茫……

【问题讨论】:

    标签: swift function core-data nsmanagedobject


    【解决方案1】:

    我不确定为什么这个引用是模棱两可的。 willChangeValueForKey 有另一个实现,但你的函数声明应该澄清它。

    虽然在这种情况下,使这个函数通用并没有帮助你。这个函数在非泛型形式中同样有用,幸运的是,它没有不明确的引用问题。这个版本仍然处理NSManagedObject 实例和子类实例:

    func coredataSetter(entity: NSManagedObject, attribute: CustomStringConvertible, value: String) {
        entity.willChangeValueForKey(attribute.description)
        entity.setPrimitiveValue(value, forKey: attribute.description)
        entity.didChangeValueForKey(attribute.description)
    }
    

    【讨论】: