NSFetchedResultsController可以使用NSDictionaryResultType吗?

时间:2015-01-27 13:21:48

标签: ios cocoa core-data nsfetchedresultscontroller

我使用核心数据来存储商店Entity商店和我拥有Attribute城市的每家商店,我想按城市对商店进行分组,并提供UITableView所有商店城市。我使用NSFetchedResultsController来获取数据并刷新UITableView,因为我想对城市进行分组,所以我将请求的resultType设置为NSDictionaryResultType。 但是现在,当我在objectAtIndexPath NSFetchedResultsController使用NSKnownkeysdictionary1时,我得到NSFetchedResultsController我的问题是,我可以NSDictionaryResultType处理NSFetchedResultsController,或者我应该放弃使用在这种情况下{{1}}并采取其他方法?

1 个答案:

答案 0 :(得分:1)

您必须为其设置NSExpressionDescription以获取适当的值。你可以这样做,

- (NSFetchedResultsController *)fetchedResultsController
{
    if (!_fetchedResultsController) {
        NSExpression *cityKeypath = [NSExpression expressionForKeyPath:@"identifier"];
        NSExpressionDescription *cityDescription = [[NSExpressionDescription alloc] init];
        cityDescription.expression = cityKeypath;
        cityDescription.name = @"City";
        cityDescription.expressionResultType = NSStringAttributeType;


        NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Shop"];
        [fetchRequest setPropertiesToFetch:@[cityDescription]];
        [fetchRequest setPropertiesToGroupBy:@[@"city"]];
        [fetchRequest setResultType:NSDictionaryResultType];

        fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"city" ascending:YES]];
        _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                        managedObjectContext:self.managedObjectContext
                                                                          sectionNameKeyPath:nil
                                                                                   cacheName:nil];

       _fetchedResultsController.delegate = self;
        NSError *error;

        [_fetchedResultsController performFetch:&error];
    }
    return _fetchedResultsController;
}

因此,您需要为要获取的属性提供NSExpressionDescription。 NSFetchedResultsController结果将以字典类型显示,

 {
   @"city": "Kansas"
  }
 ...