核心数据 - 不同结果在fetchedResultsController中不起作用

时间:2012-03-03 12:14:17

标签: iphone core-data

我花了好几个小时试图计算出以下内容...

我的iPhone App中有以下Core Data fetchResultsController,尽管在我的代码中设置了以下内容,但它并没有返回一组不同的值...

// Only distinct values
[fetchRequest setReturnsDistinctResults:YES];

以下是整个fetchResultController ...

- (NSFetchedResultsController *)fetchedResultsController
{
    if (__fetchedResultsController != nil) {
        return __fetchedResultsController;
}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

[fetchRequest setEntity:[NSEntityDescription entityForName:@"CardMessage"inManagedObjectContext:self.managedObjectContext]];

// Set the properties to fetch
NSArray *propertiesToFetch = [[NSArray alloc] initWithObjects:@"category", nil];
[fetchRequest setPropertiesToFetch:propertiesToFetch];

// Only distinct values
[fetchRequest setReturnsDistinctResults:YES];

// Order the output
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"category" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

[fetchRequest setSortDescriptors:sortDescriptors];

// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc]
                        initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext
                        sectionNameKeyPath:nil
                        cacheName:@"Master"];

aFetchedResultsController.delegate = self;

self.fetchedResultsController = aFetchedResultsController;

NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
    /*
     Replace this implementation with code to handle the error appropriately.

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
     */
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return __fetchedResultsController;
}    

2 个答案:

答案 0 :(得分:2)

您的propertiesToFetch数组包含一个字符串。它应该包含NSPropertyDescription。 (在这种情况下,它将是其子类NSAttributeDescription。)

NSArray *propertiesToFetch = [[NSArray alloc] initWithObjects:
   [entity.propertiesByName objectForKey:@"category"], 
   nil];

(现代Objective-C)

NSArray *propertiesToFetch = @[entity.propertiesByName[@"category"]]; 

如果您仍然获得双重条目,只需使用NSSet即可获得唯一值。

NSSet *uniqueProperties = [NSSet setWithArray:resultsArray]; 

答案 1 :(得分:0)

请注意setPropertiesToFetch文档中的备注:

  1. 在设置此值之前,必须为获取请求设置实体,否则NSFetchRequest会抛出NSInvalidArgumentException异常。

  2. 仅当resultType设置为NSDictionaryResultType时才使用此值。

  3. 请注意,resultType的默认值为NSManagedObjectResultType。