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

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

【问题讨论】:

    标签: ios cocoa core-data 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 都做不到
    • 获取的对象应该给你字典数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 2018-02-16
    • 2020-06-30
    • 2014-11-15
    • 2011-12-07
    • 2011-11-20
    相关资源
    最近更新 更多