Retired Document
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.
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"];
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]];
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:
isnil
), 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.
Create a date formatter object to display the time information.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
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.
Copyright © 2005, 2013 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2013-09-18