过滤NSFetchedResultsController以删除具有相同名称的对象

时间:2011-12-14 18:47:49

标签: iphone ios core-data nspredicate nsfetchedresultscontroller

我有这些对象是唯一的,除了两列我用作UITableView中的显示。由于这个原因,UITableView通常会显示重复项。我需要以某种方式过滤掉这些重复项。

在这种情况下,在FetchResult上设置distinctResult将不起作用,因为这限制了NSFetchedResultsController的功能,并且它要求REsultType是NSDictionary而不是托管对象的子类。

有没有人知道如何使用谓词过滤掉这些重复项?请记住,这些对象上的每个字段都是唯一的,除了其中两个。

-(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.

}

1 个答案:

答案 0 :(得分:0)

虽然设置一个可选的一对一关系可能更容易(例如,“child”),以便你可以使用NSPredicate获取“child == nil”,你当然可以过滤使用[array enumerateObjectsUsingBlock:]或等价物在纯物镜C中足够容易,并且只根据您的条件将唯一对象添加到结果数组中。