Search code examples
ioscocoacore-datansfetchedresultscontroller

Can NSFetchedResultsController work with NSDictionaryResultType?


I use Core Data to store shops as Entity Shop and on every shop I have an Attribute city, I want to group the shops by city and present a UITableView with all the cities. I use NSFetchedResultsController to fetch the data and refresh the UITableView and since I want to group the cities I set the resultType of the request as NSDictionaryResultType. However now when I use objectAtIndexPath at my NSFetchedResultsController I am getting NSKnownkeysdictionary1 My question is can I make the NSFetchedResultsController handle the NSDictionaryResultTypeor I should drop the use of NSFetchedResultsController in this case and take some other approach?


Solution

  • You have to set the NSExpressionDescription for it to fetch the appropriate value. You could do it like this,

    - (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;
    }
    

    So, you need to provide NSExpressionDescription for the properties you want to fetch. The NSFetchedResultsController result will in in dictionary type like this,

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