views:

726

answers:

2

I have a NSFetchedResultsController which is fetching objects from a NSManagedObjectContext.

These objects have a lastOpened property, which is initially nil and is only set when they are viewed.

I want my UITableView to display a list of the most recently opened objects, which I can do by adding a NSSortDescriptor to the NSFetchRequest.

Question:

I don't want to display the objects which have never been studied. (lastOpened == nil) Can I sort this via the same NSFetchRequest? Is there a better way to filter the data?

Thanks.

+2  A: 

Try this:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"lastOpened != nil"];
... // add sort descriptors etc.

Then add the fetch request to the NSFetchResultsController.

Diederik Hoogenboom
+3  A: 

Absolutely. What you're looking for is an NSPredicate. Basically, it allows you to specify one or more conditions that you want your fetched objects to meet, then only fetches objects that match those conditions.

Building predicates is a slightly tricky proposition, however - you might want to take a look at the Predicate Format String Syntax guide to get started. For your particular case, it's even trickier since I'm not sure there's a representation for the nil value in predicate terms. You can get around this, however, by using some date in the distant past:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lastOpened > %@",
                          [NSDate dateWithTimeIntervalSince1970:0]];

You can just check against nil directly in a predicate:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lastOpened != nil"];

This creates a predicate that only allows objects with a set date (anything after January 1, 1970) to be returned. You'd then add the predicate to the fetch request before you execute it:

// Assuming you have some almost-ready NSFetchRequest *request:
[request setPredicate:predicate];
Tim
This is fantastic. I had a hunch predicates were involved. Thanks!
Michael Grinich