Reputation: 1442
Ive watched the 2016 WWDC Video on Core Data and viewed various tutorials. I have seen various ways of creating an object to persist into the managedObjectContext with the Core Data Framework.
In the example I have Day
as an entity. I would like to create a new Day
object for each new day that the user uses the application.
I have come across:
1st option
let entity = NSEntityDescription.insertNewObject(forEntityName: "Day", into: CoreDataHelper.context)
let object = NSManagedObject(entity: entity, insertInto: CoreDataHelper.context)
2nd option
let object = Day(entity: Day.entity(), insertInto: CoreDataHelper.context)
3rd option
let object = Day(context: CoreDataHelper.context)
and know there have been other possibilities people have come up with as well.
What is the difference between the bottom two options, as I did not see a demonstration of the second option in the WWDC Video. Does the third option automatically insert into the managedObjectContext or should there be a certain approach taken to insert the object into the context to then retrieve all objects using the NSFetchedResultsController.
Upvotes: 4
Views: 1604
Reputation: 6635
The second option is the designated initializer on NSManagedObject
, which Day
subclasses.
The third option is a convenience initializer defined on Day
that invokes option 2.
The first option is nonsense. 🤔 The first line creates an instance of Day
inserted into the context, just like option 2 and 3. The second line attempts to create an instance of Day
by passing an instance of Day
to a parameter that is expecting an NSEntityDescription
. I suspect option 1 is supposed to look like:
let entity = NSEntityDescription.entity(forEntityName: "Day", in: CoreDataHelper.context)
let object = NSManagedObject(entity: entity, insertInto: CoreDataHelper.context)
All of the options have the same result. I'm not sure why there are so many variations. That would be a question only Apple could answer. Hope this was helpful!
Upvotes: 6