The 2 code samples, able to insert new object into CoreData.
I was wondering, is there any difference among NSManagedObject(context:)
and NSEntityDescription.insertNewObject
, when comes to inserting new object?
When we should choose one over another?
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)")
}
}
}
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)")
}
}
}
Here's what the docs say for each of them.
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.
The first one was introduced in iOS 10
and makes it more natural how the instantiation of the NSManagedObject
should look like.
There are following differences in the two -
String
for entityName - so it is error prone, while the first method always works with your NSManagedObject
subclass without having to use String
y name.This method is only legal to call on subclasses of NSManagedObject that represent a single entity in the model.
, Animal > Dog