2016-01-13 78 views
0

我想创建一个全局函数,所以我的核心数据类可以使用此函数来创建自定义setter。但我越来越`暧昧使用“willChangeValueForKey”自定义setter/getter函数核心数据

我正在使用的代码是:

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

我有点迷茫......

回答

0

我不知道为什么该引用是模糊的。还有的willChangeValueForKey另一种实现方式,但你的函数声明应该澄清。

让该功能一般不是帮助你在这种情况下,虽然这个功能会同样使用幸运的是,它没有模棱两可的参考问题。此版本仍处理NSManagedObject实例和子类实例:

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