Search code examples
iosobjective-ccore-datansfetchedresultscontrollernsfetchrequest

iOS Coredata: Refetch of subcategories necessary?


I'm optimizing my app at the moment. My table structure is simplified as this:

MainCategory

  • name
  • position
  • hasSubcategories

SubCategory

  • name
  • position
  • belongsToMainCategory

Now if a user selects in the first view controller a main category he's segued to the next showing all subcategories for a certain main category. So far with the following code:

- (void)setupFetchedResultsController
{
    NSError *error = nil;
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SubCategory"];
    request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"position" ascending:YES]];
    [self.mainCategory.managedObjectContext executeFetchRequest:request error:&error];
    request.predicate = [NSPredicate predicateWithFormat:@"belongsToMainCategory = %@", self.mainCategory];

    self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request
                                                                       managedObjectContext:self.mainCategory.managedObjectContext
                                                                         sectionNameKeyPath:nil
                                                                                  cacheName:nil];
}

Now I've started to wonder if I even need to do that since if I set my data model as the main category I have all infos in the mainCategory.hasSubcategories. However how are these objects sorted? Or is it really easier just to refetch as I currently do?


Solution

  • My simple suggestion is to stay with that code. If you access to mainCategory.hasSubcategories you will have a NSSet that is not ordered. So, you need to order yourself.

    In my code if I need to do like you do, I usually use this pattern. It's quite simple and can be reused. In addition, if you are worried about performances no worry. Core Data under the hood maintains a cache that allows you to boost retrieval performances.

    If you want to speed up things you could also rely on setRelationshipKeyPathsForPrefetching method of NSFetchRequest class.