Ios 核心数据:insertNewObject和指定初始值设定项之间有什么区别
我找到了两种解决问题的方法:Ios 核心数据:insertNewObject和指定初始值设定项之间有什么区别,ios,objective-c,swift,core-data,nsmanagedobjectcontext,Ios,Objective C,Swift,Core Data,Nsmanagedobjectcontext,我找到了两种解决问题的方法: public class MyClass: NSManagedObject { init(_ entity:NSEntityDescription, dict: NSDictionary, context: NSManagedObjectContext) { super.init(entity: entity , insertInto: context) } } let entity = NSEntityDescription.en
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!)
及
但我最终无法理解两者之间的区别。它是如何影响NSManagedObjectContext的?它们具有相同的效果。
NSEntityDescription
上的方法是一种“工厂”方法,在Objective-C中不太常见(该方法早于Swift)。但最终结果与使用指定的初始值设定项相同。尽管factory方法的代码不可用,但您可以假设它在某个点调用指定的初始值设定项。init(实体:NSEntityDescription,插入到上下文:NSManagedObjectContext?可用于iOS 3.0的初始值设定项+
init(上下文:NSManagedObjectContext)可用于iOS 10.0的初始值设定项+
我使用这两个初始值设定项来保持与iOS<10.0的兼容性,它们之间没有区别。我不知道第一个版本,但我为您准备了第三个版本:
let createe=MyClass(context:context)
,我更愿意避免知道实体名称的需要。是否提到insertNewObject和init之间的关系
let myClass = NSEntityDescription.insertNewObject(forEntityName: "MyClass", into: context) as! MyClass