Important: This document describes behavior on old releases of OS X and no longer represents best practices for OS X v10.8 and later or iOS 6 and later.
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.
mainfunction, 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"];
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]
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
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");
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.
Create a date formatter object to display the time information.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
Print out the run history for the process.
NSLog(@"%@ run history:", [processInfo processName]);
for (Run *aRun in fetchedArray)
NSLog(@"On %@ as process ID %ld",
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.