Listing Previous Runs

This section shows you how to fetch all the Run instances from the persistent store.

Fetching Run Objects

Create and Execute the Fetch Request

The first step is to create the fetch request. You want to fetch instances of the Run entity and order the results by recency. You need to set the entity for the fetch request to be the Run entity, and create and set an appropriate array of sort orderings. Finally, you perform the fetch by sending the managed object context an executeFetchRequest:request error: message.

bullet
To Create and execute a fetch request
  1. In the main function, immediately after the code you added in the previous chapter, create a new fetch request for the entity named “Run”.

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Run"];
  2. Create a new sort descriptor to arrange the fetch results by recency.

    Set the sort descriptor for the fetch—note that you must supply an array of sort descriptors.

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
            initWithKey:@"date" ascending:YES];
    [request setSortDescriptors:@[sortDescriptor]];
  3. Execute the fetch request by sending it to the managed object context.

    Recall that you declared an error in the previous chapter. If there is an error (if value returned by executeFetchRequest:error: is nil), report it and exit.

    error = nil;
    NSArray *fetchedArray = [moc executeFetchRequest:request error:&error];
    if (fetchedArray == nil)
    {
        NSLog(@"Error while fetching\n%@",
                ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
        exit(1);
    }

Display the Results

To display the results of the fetch request, simply iterate through the array of fetched run objects and log the run information. Format the date appropriately using a date formatter.

bullet
To display the fetch results
  1. Create a date formatter object to display the time information.

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
  2. Print out the run history for the process.

    NSLog(@"%@ run history:", [processInfo processName]);
     
    for (Run *aRun in fetchedArray)
    {
        NSLog(@"On %@ as process ID %ld",
                [formatter stringForObjectValue:aRun.date],
                aRun.processID);
    }

Build and Test

Build and run the utility. It should compile without warnings. When you run the utility, it should not log any errors. It should properly display the run history.