Mac OS X Reference Library Apple Developer
Search

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.

  1. In the main function, immediately after the code you added in the previous chapter, create a new fetch request and set the entity (recall that in the previous chapter you retrieved the Run entity description to create the new instance of Run).

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:runEntity];
  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:[NSArray arrayWithObject: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, report it and exit.

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

Display the Results

Iterate through the array of fetched run objects and log the run information.

  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 in array)
    {
        NSLog(@"On %@ as process ID %d",
                [formatter stringForObjectValue:run.date],
                run.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.




Last updated: 2010-05-24

Did this document help you? Yes It's good, but... Not helpful...