我找到了两个解决问题的办法:
public class MyClass: NSManagedObject {
init(_ entity:NSEntityDescription, dict: NSDictionary, context: NSManagedObjectContext) {
super.init(entity: entity , insertInto: context)
}
}
let entity = NSEntityDescription.entity(forEntityName: "MyClass", in: self.context!)
_ = MyClass.init(entity!, dict: item as! NSDictionary, context: self.context!)
和
let myClass = NSEntityDescription.insertNewObject(forEntityName: "MyClass", into: context) as! MyClass
但我最终无法理解其中的区别。它如何影响 NSManagedObjectContext
?
最佳答案
效果相同。 NSEntityDescription
上的方法是一个“工厂”方法,您在 Objective-C 中很少见到这种方法(该方法在 Swift 出现之前就已存在)。但最终结果与使用指定初始化程序相同。虽然工厂方法的代码不可用,但您可以假设它在某个时候调用了指定的初始化程序。
关于ios - 核心数据 : What difference between insertNewObject vs designated initializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41043450/