ios - NSFetchedResultsController 可以与 NSDictionaryResultType 一起使用吗?

标签 ios cocoa core-data nsfetchedresultscontroller

我使用核心数据将商店存储为实体商店,并且在每个商店上我都有一个属性城市,我想按城市对商店进行分组并呈现UITableView 包含所有城市。我使用 NSFetchedResultsController 来获取数据并刷新 UITableView,因为我想对城市进行分组,所以我将请求的 resultType 设置为 NSDictionaryResultType。 但是现在,当我在 NSFetchedResultsController 上使用 objectAtIndexPath 时,我得到 NSKnownkeysdictionary1 我的问题是我可以制作 NSFetchedResultsController 句柄吗? NSDictionaryResultType 或者我应该在这种情况下放弃使用 NSFetchedResultsController 并采取其他方法?

最佳答案

您必须为其设置 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"
  }
 ...

关于ios - NSFetchedResultsController 可以与 NSDictionaryResultType 一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28171562/

相关文章:

ios - 构建失败——属性必须具有已定义的类型

ios - com.apple.gamed 在删除游戏时崩溃

ios - 恢复 Xcode 版本项目

ios - 快速比较两个数组并删除具有不匹配的特定字段的元素

objective-c - NSView 的绘图上下文

ios - Xcode - 如何修复 'NSUnknownKeyException' ,原因 : … this class is not key value coding-compliant for the key X"error?

ios - 如何形成谓词以从包含来自数组的字符串元素的核心数据中获取对象

iOS - 执行期间的对象释放

ios - Postman Body 对 Swift Alamofire 的原始请求

iphone - 我怎样才能画出弯曲的阴影?