简体   繁体   中英

Why use NSFetchedResultsController when inserting Core Data objects?

I'm trying to get my head around Core Data on the iphone.

This is code from Apple's 'Navigation based app using Core data' template (method - insertNewObject)

// Create a new instance of the entity managed by the fetched results controller.
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];

It seems completely counter intuitive to me that the fetched results controller is used when inserting a new object.

I changed the code to this:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] 
                                                                  inManagedObjectContext:managedObjectContext];

which works just as well and does not require access to the fetch request.

Am I missing something here? Is there any good reason to use the fetched results controller in the insert method?

The purpose of using the fetchedResultsConstroller in the Apple sample is to obtain the Entity type. The obvious benefit that I see is that you're guaranteed type safety for the insert. Whereas in your re-factored version you hard-code the entity type.

Although this isn't a big deal if you were to change the entity name to say, Event2, you would then have to change the hard-coded NSString (@"Event").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM