small medium large xlarge

Back to: All Forums  Core Data
Generic-user-small
17 Dec 2009, 06:55
Nevan (10 posts)

The answer to this question may be “That’s just the way it is”, but it’s something that’s been bugging me.

Whenever I go to type an NSFetchRequest execute, I always start like this:

NSArray *array = [request executeFetchRequest];

</code>

and then remember that it doesn’t work like this. I have to execute it against the managed object complex instead, like this:

NSArray *array = [moc executeFetchRequest:request error:&error];

</code>

The first way seems more logical to me, since we already know what the managed object complex is, after giving it here:

[request setEntity: [NSEntityDescription
  entityForName:@"Recipe" inManagedObjectContext:moc]];

</code>

Is there any reason for the pattern Apple uses?

Photo_2_pragsmall
19 Dec 2009, 00:08
Kurt Arnlund (4 posts)
[request setEntity: [NSEntityDescription
  entityForName:@"Recipe" inManagedObjectContext:moc]];

This is creating an entity description and then storing it in the NSFetchRequest. The managed object context is never stored in any of these objects. Break it apart into its two actions:

create the entity description

[NSEntityDescription
  entityForName:@"Recipe" inManagedObjectContext:moc]

set the entity description into the request

[request setEntity:  <entity description>  ];

So the entity description is merely using the managed object context parameter to initialize itself. It never stores the managed object context. I think that’s the point of Apples design here. Few objects hold on to the managed object context - your app is the one responsible for holding that context. And hence that’s why that context should be the first think you think about when you think about performing a fetch. The managed object context is your apps main entry to CoreData.

Hope that helps.

You must be logged in to comment