Search code examples
iosxcodecore-datauiviewcontrollernsfetchrequest

Fill an array using NSFetchRequest (CoreData)


I created a project for iPad which uses Apple's "Use CoreData" template.

I customized several things, e.g. the names of the objects, but the system stayed the same.

Apple uses a MasterViewController.h which is a UITableViewController und a DetailViewController.h which is a simple UIViewController. Once you have selected one of the objects in the UITableView in MasterViewController.h it gives its attributes to the DetailViewController.

Now the problem:

I created a third view controller, named ResultsViewController.h which should display all the data (attributes of the objects).

I want to use one or more NSArray(s), which should contain all my data (not just the selected but all. So if you created 5 objects, you want to have 5 times NSArray).

(1) How can I fetch the values of the xcoredatamodel to be able to access them in ResultsViewController? Sending a fetch request did not work for me?

(2) How can I determine how many objects I created in my UITableView (MasterViewController.h)?

CoreData Structure:

Simple, one entity, several attributes, that is it!

Thanks a lot!


Solution

  • First: you should not put all your data into arrays. This will result in memory problems once your data volume grows. Core data is actually designed to fetch the data you need very efficiently without the need of maintaining expensive parallel data structures.

    So the preferred way is to pass the same NSManagedObjectContext to the ResultsViewControllerand have it fetch its own data as needed.

    However, if you really want to fetch all the data, it is simple.

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityName"
          inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext
          executeFetchRequest:fetchRequest error:&error];
    [fetchRequest release];
    

    The array fetchedObjects now contains all of your data. You can access the attributes in the usual way (e.g. with dot notation or KVC).