views:

523

answers:

2

I have a fetchedResultsController that has returned all records for my entity "Account".

I would like to quickly search all Account records for the attribute "lastName" == value, and give me back the Account object, or at least the indexPath of the object in the fetchedResultsController. There should only be 1 object returned.

Other than iterate through every objectAtIndexPath, is there a better way to search the fetchController using NSPredicate?

A: 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// set up fetch request
...
NSPredicate *requestPredicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(lastName like '%@')", self.lastName]];
[fetchRequest setPredicate:requestPredicate];
...
// perform fetch
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) { 
    // handle error...
}

...

Account *uniqueAccount = [[self.fetchedResultsController fetchedObjects] anyObject]; // assuming lastName attribute is unique
Alex Reynolds
thanks Alex - so are you saying I should ignore the already setup fetchedResultsController that builds my NSTableView, and create an additional one for this purpose? I guess what I'm saying is, I cannot do an NSPredicate on the already retrieved Account objects in fetchedResultsController?
mootymoots
Yes, you can apply a predicate to an existing `NSSet` or `NSArray`. No, you don't need to create an additional FRC. See: http://theocacao.com/document.page/346
Alex Reynolds
+7  A: 

mootymoots, just filter the fetched objects with another predicate...

NSPredicate *lastNameMatch = ...
NSArray *matchingFetchedObjects = [fetchedResultsController.fetchedObjects filteredArrayUsingPredicate:lastNameMatch];

That leaves your fetchedResultsController results un-altered, but gives you an array with a match for the last name predicate.

ohhorob