I have these objects that are unique except for two columns once of which I am using as the display in the UITableView. The UITableView will often show duplicates due to this. I need to filter out these duplicates somehow.
Setting distinctResult on the FetchResult won’t work in this case since that limits the functionality of the NSFetchedResultsController and it requires that the REsultType be a NSDictionary instead of a subclass of managed object.
Doesn’t anyone have any idea how I can filter these duplicates out using a predicate?? Remember that every field on these objects is unique except for two of them.
-(NSFetchedResultsController *) fetchGroupedObjects:(NSString *)entityDescription
sortField:(NSString *)sortField
withPredicate:(NSPredicate *)predicate {
BPRAppDelegate *delegate = (BPRAppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = delegate.managedObjectContext;
//NSError *error;
//Fetch the data....
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:entityDescription inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSSortDescriptor *groupDescription = [[NSSortDescriptor alloc]
initWithKey:GROUP_NAME ascending:YES];
//Sort by Category Name
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey:sortField ascending:YES];
NSMutableArray *sorts = [[[NSMutableArray alloc] init] autorelease];
[sorts addObject:sortDescriptor];
[sorts addObject:groupDescription];
[fetchRequest setSortDescriptors:sorts];
//[fetchRequest setResultType:NSDictionaryResultType];
//[fetchRequest setPropertiesToGroupBy:[entity.propertiesByName valueForKey:CONTRACTOR_NAME];
if (predicate != nil)
[fetchRequest setPredicate:predicate];
//NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
//NSFetchResultsController
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *fetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:context sectionNameKeyPath:GROUP_NAME
cacheName:nil]; //Don't use a cache
[fetchRequest release];
[sortDescriptor release];
[groupDescription release];
return fetchedResultsController; //You can't autorelease this thing... the requestor must do that.
}
While it might be easier to set up an optional to-one relationship back to itself (say, “child”) so that you can then fetch with a NSPredicate where “child == nil”, you can certainly post-filter easily enough in pure objective C using
[array enumerateObjectsUsingBlock:]or equivalent, and only add unique objects per your criteria to the resultant array.