NSFetchedResultsController 可以与 NSDictionaryResultType 一起使用吗?

Posted

技术标签:

【中文标题】NSFetchedResultsController 可以与 NSDictionaryResultType 一起使用吗?【英文标题】:Can NSFetchedResultsController work with NSDictionaryResultType? 【发布时间】:2015-01-27 13:21:47 【问题描述】:

我使用 Core Data 将商店存储为 EntityShop 并且在每个商店中我都有一个 Attribute 城市,我想按城市对商店进行分组,并在所有城市中显示一个 UITableView。我使用NSFetchedResultsController 来获取数据并刷新UITableView,因为我想对城市进行分组,所以我将请求的resultType 设置为NSDictionaryResultType。 但是现在当我在我的NSFetchedResultsController 上使用objectAtIndexPath 时,我得到NSKnownkeysdictionary1 我的问题是我可以让NSFetchedResultsController 处理NSDictionaryResultType 或者在这种情况下我应该放弃使用NSFetchedResultsController 并采取一些其他方法?

【问题讨论】:

【参考方案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"
  
 ...

【讨论】:

它似乎可以工作,但我如何访问 cellForRowAtIndexPath 的字典?看来NSFetchedResultsController 中的objectAtIndexPathfetchedObjects 都做不到 获取的对象应该给你字典数组。

以上是关于NSFetchedResultsController 可以与 NSDictionaryResultType 一起使用吗?的主要内容,如果未能解决你的问题,请参考以下文章

在 Core Data 应用程序中调用 performFetch 后,是不是需要手动更新表视图?