views:

69

answers:

1

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?

+1  A: 

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").

mmccomb
Ok but I could achieve type safety by declaring an ivar to hold the entity name or by using a #define statement. The line I inserted staring NSEntityDescription is copied from the 'fetchedResultsController' method so @"Event" has to be hard-coded somewhere, I still don't see the benefit of using the fetch request.
Joe
Alternatively, you could create a constant which holds the entity name and use that in both the fetchedResultsController and insertNewObject methods?
mmccomb
Yes, that's what I meant.
Joe
That looks like the best approach to me!
mmccomb