Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
This chapter is from the book

Displaying Your Managed Objects

To display or use existing entity data in an app, managed objects need to be fetched from the managed object context. Fetching is analogous to running a query in a relational database, in that you can specify what entity you want to fetch, what criteria you want your results to match, and how you want your results sorted.

Creating Your Fetch Request

The object used to fetch managed objects in Core Data is called NSFetchRequest. Refer to ICFFriendChooserViewController in the sample app. This view controller displays the friends set up in Core Data and allows the user to select a friend to lend a movie to (see Figure 13.6).

Figure 13.6

Figure 13.6 Sample App: Friend Chooser.

To get the list of friends to display, the view controller performs a standard fetch request when the view controller has loaded. The first step is to create an instance of NSFetchRequest and associate the entity to be fetched with the fetch request:

NSManagedObjectContext *moc = kAppDelegate.managedObjectContext;

NSFetchRequest *fetchReq = [[NSFetchRequest alloc] init];

NSEntityDescription *entity =
 [NSEntityDescription entityForName:@"Friend"

[fetchReq setEntity:entity];

The next step is to tell the fetch request how to sort the resulting managed objects. To do this, we associate a sort descriptor with the fetch request, specifying the attribute name to sort by:

NSSortDescriptor *sortDescriptor =
 [[NSSortDescriptor alloc] initWithKey:@"friendName"

NSArray *sortDescriptors =
 [NSArray arrayWithObjects:sortDescriptor, nil];

[fetchReq setSortDescriptors:sortDescriptors];

Since the friend chooser should show all the available friends to choose from, it is not necessary to specify any matching criteria. All that remains is to execute the fetch:

NSError *error = nil;

self.friendList = [moc executeFetchRequest:fetchReq

 if (error)
  NSString *errorDesc =
   [error localizedDescription];

  UIAlertView *alert =
   [[UIAlertView alloc] initWithTitle:@"Error fetching friends"
  [alert show];

To execute a fetch, create an instance of NSError and set it to nil. Then have the managed object context execute the fetch request that has just been constructed. If an error is encountered, the managed object context will return the error to the instance you just created. The sample app will display the error in an instance of UIAlertView. If no error is encountered, the results will be returned as an NSArray of NSManagedObjects. The view controller will store those results in an instance variable to be displayed in a table view.

Fetching by Object ID

When only one specific managed object needs to be fetched, Core Data provides a way to quickly retrieve that managed object without constructing a fetch request. To use this method, you must have the NSManagedObjectID for the managed object.

To get the NSManagedObjectID for a managed object, you must already have fetched or created the managed object. Refer to ICFMovieListViewController in the sample app, in the prepareForSegue:sender: method. In this case, the user has selected a movie from the list, and the view controller is about to segue from the list to the detail view for the selected movie. To inform the detail view controller which movie to display, the objectID for the selected movie is set as a property on the ICFMovieDisplayViewController:

if ([[segue identifier] isEqualToString:@"showDetail"])

  NSIndexPath *indexPath =
   [self.tableView indexPathForSelectedRow];

  ICFMovie *movie =
   [[self fetchedResultsController]

  ICFMovieDisplayViewController *movieDispVC =
   (ICFMovieDisplayViewController *)
   [segue destinationViewController];

  [movieDispVC setMovieDetailID:[movie objectID]];

When the ICFMovieDisplayViewController is loaded, it uses a method on the managed object context to load a managed object using the objectID:

ICFMovie *movie = (ICFMovie *)[kAppDelegate.managedObjectContext

[self configureViewForMovie:movie];

When this is loaded, the movie is available to the view controller to configure the view using the movie data (see Figure 13.7).

Figure 13.7

Figure 13.7 Sample App: Movie Display view.

It is certainly possible to just pass the managed object from one view controller to the next with no problems, instead of passing the objectID and loading the managed object in the destination view controller. However, there are cases when using the objectID is highly preferable to using the managed object:

  • If the managed object has been fetched or created on a different thread than the destination view controller will use to process and display the managed object—this approach must be used since managed objects are not thread safe!
  • If a background thread might update the managed object in another managed object context between fetching and displaying—this will avoid possible issues with displaying the most up-to-date changes.

Displaying Your Object Data

After managed objects have been fetched, accessing and displaying data from them is straightforward. For any managed object, using the key-value approach will work to retrieve attribute values. As an example, refer to the configureCell:atIndexPath method in ICFFriendsViewController in the sample app. This code will populate the table cell’s text label and detail text label.

NSManagedObject *object =
 [self.fetchedResultsController objectAtIndexPath:indexPath];

cell.textLabel.text = [object valueForKey:@"friendName"];

NSInteger numShares = [[object valueForKey:@"lentMovies"] count];

NSString *subtitle = @"";

switch (numShares)
  case 0:
    subtitle = @"Not borrowing any movies.";

  case 1:
    subtitle = @"Borrowing 1 movie.";

    subtitle =
     [NSString stringWithFormat:@"Borrowing %d movies.",


cell.detailTextLabel.text = subtitle;

To get the attribute values from the managed object, call valueForKey: and specify the attribute name. If the attribute name is specified incorrectly, the app will fail at runtime.

For managed object subclasses, the attribute values are also accessible by calling the property on the managed object subclass with the attribute name. Refer to the configureViewForMovie: method in ICFMovieDisplayViewController in the sample app.

- (void)configureViewForMovie:(ICFMovie *)movie

  NSString *movieTitleYear = [movie yearAndTitle];


  [self.movieDescription setText:[movie movieDescription]];

  BOOL movieLent = [[movie lent] boolValue];

  NSString *movieShared = @"Not Shared";
  if (movieLent)
    NSManagedObject *friend =
    [movie valueForKey:@"lentToFriend"];

    NSDateFormatter *dateFormatter =
     [[NSDateFormatter alloc] init];

    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

    NSString *sharedDateTxt =
    [dateFormatter stringFromDate:[movie lentOn]];

    movieShared =
     [NSString stringWithFormat:@"Shared with %@ on %@",
     [friend valueForKey:@"friendName"],sharedDateTxt];

  [self.movieSharedInfoLabel setText:msh];

If the property-based approach to get attribute values from managed object subclasses is used, errors will be caught at compile time.

Using Predicates

Predicates can be used to narrow down your fetch results to data that match your specific criteria. They are analogous to a where clause in an SQL statement, but they can be used to filter elements from a collection (like an NSArray) as well as a fetch request from Core Data. To see how a predicate is applied to a fetch request, refer to method fetchedResultsController in ICFSharedMoviesViewController. This method lazy loads and sets up an NSFetchedResultsController, which helps a table view interact with the results of a fetch request (this is described in detail in the next section). Setting up a predicate is simple, for example:

NSPredicate *predicate =
 [NSPredicate predicateWithFormat:@"lent == %@",@YES];

In the format string, predicates can be constructed with attribute names, comparison operators, Boolean operators, aggregate operators, and substitution expressions. A comma-separated list of expressions will be substituted in the order of the substitution expressions in the format string. Dot notation can be used to specify relationships in the predicate format string. Predicates support a large variety of operators and arguments, as shown in Table 13.2.

Table 13.2 Core Data Predicate Supported Operators and Arguments


Operators and Arguments

Basic Comparisons

=, ==, >=, =>, <=, =<, >, <, !=, <>, BETWEEN {low,high}


AND, && OR, || NOT, !






FALSE, NO, TRUE, YES, NULL, NIL, SELF. Core Data also supports string and numeric literals.

Tell the fetch request to use the predicate:

[fetchRequest setPredicate:predicate];

Now the fetch request will narrow the returned result set of managed objects to match the criteria specified in the predicate (see Figure 13.8).

Figure 13.8

Figure 13.8 Sample App: Shared Movies tab.

  • + Share This
  • 🔖 Save To Your Account