Search code examples
iphoneobjective-cioscore-datansfetchrequest

Core Data fault: how to load an entities relationship set of objects correctly


For example:

I have two entities named Projectand Todo where a project has many todos (to-many relationship) and each todo has one Project(see image).

CoreData setup of entities

In my ViewController.h I have something like:

...
NSArray *projectArray;
NSArray *todosArray;

@property (nonatomic,retain) NSArray *projectArray;
@property (nonatomic,retain) NSArray *todosArray;
...

In my ViewController.m I have something like:

...
@synthesize projectArray,todosArray;
...
self.projectArray = [self fetchRequestForAllProjects];
...

The user has an interface where he is able to select between all different projects. As soon as the user selects a project, the related todo objects have to be set to be loaded and presented.

Question 1: How do I load the set of todos into the todosArray in the best way?

I was doing it like that (also in the ViewController.m):

...
// after deselecting a project entry I reset the todosArray
self.todosArray = nil;
...
//when the user selects a new project I reset the todosArray like this:
self.todosArray = [selectedProject.todos allObjects];
...

But somehow the app very rarely crashes in the last line of code. Is there any problem with my code?

Question 2: Would it be better to use another fetch request for the todos Objects?

UPDATE:

I am using the todosArrayin various methods of the ViewController.m:

(a) get the count of objects, (b) present each todos entry inside a table view row, and (c) to identify the selected todo entry (threw row selection)


Solution

  • Answer #1

    It is best to sort them when you pull everything out of the set into an array. This will keep your user experience consistent:

    NSSet *projectTodoEntities = [mySelectedProject valueForKey:@"todos"];
    NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"myKey" ascending:YES];
    NSArray *sortedToDos = [projectTodoEntities sortedArrayUsingDescriptors:[NSArray arrayWithObject:sorter]];
    

    Answer #2

    No, fetching is expensive compared to just accessing a relationship. A fetch will hit disk, etc.