2个代码示例,能够将新对象插入到CoreData中。
我想知道,在插入新对象时,NSManagedObject(context:)
和 NSEntityDescription.insertNewObject
之间有什么区别吗?
什么时候我们应该选择一种而不是另一种?
NSManagedObject(上下文:)
let coreDataStack = CoreDataStack.INSTANCE
let backgroundContext = coreDataStack.backgroundContext
backgroundContext.perform {
let nsTabInfo = NSTabInfo(context: backgroundContext)
nsTabInfo.name = "..."
if backgroundContext.hasChanges {
do {
try backgroundContext.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
NSEntityDescription.insertNewObject
let coreDataStack = CoreDataStack.INSTANCE
let backgroundContext = coreDataStack.backgroundContext
backgroundContext.perform {
let nsTabInfo = NSEntityDescription.insertNewObject(forEntityName: "NSTabInfo", into: backgroundContext) as! NSTabInfo
nsTabInfo.name = "..."
if backgroundContext.hasChanges {
do {
try backgroundContext.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
最佳答案
以下是文档对每个内容的说明。
convenience init(context moc: NSManagedObjectContext)
Initializes a managed object subclass and inserts it into the specified managed object context.
This method is only legal to call on subclasses of NSManagedObject that represent a single entity in the model.
class func insertNewObject(forEntityName entityName: String,
into context: NSManagedObjectContext) -> NSManagedObject
Creates, configures, and returns an instance of the class for the entity with a given name.
This method makes it easy for you to create instances of a given entity without worrying about the details of managed object creation. The method is conceptually similar to the following code example.
第一个是在 iOS 10
中引入的,它使 NSManagedObject
的实例化看起来更加自然。
两者有以下区别 -
- 第二种方法强制您使用
String
作为entityName - 因此很容易出错,而第一种方法始终适用于您的NSManagedObject
子类,而无需使用字符串
y 名称。 - 第一个比第二个更具可读性。
- 第一个方法有一个限制 -
此方法只能合法地调用代表模型中单个实体的 NSManagedObject 子类。
,如果您这样做,这可能会产生问题在数据模型中使用实体子类化,例如。文档中的这一行指的是多个实体使用相同类名的数据模型。这是不寻常但合法的。实体继承不会影响这一点。Animal > Dog
关于ios - NSManagedObject(context :) constructor and NSEntityDescription. insertNewObject 用于将新对象插入到 CoreData 中的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67980475/