Search code examples
nssortdescriptormagicalrecordkvc

MagicalRecord sorting using by KVC


I used KVC until now to access object's properties.

In my object i have a method like this:

-(Address *)mainAddress {
    if (self.addresses != nil) {
        return [self.addresses anyObject]; //stub method
    }
    else {
        return nil;
    }
}

I can use this method with KVC using

mystring = [cliente valueForKeyPath:@"mainAddress.city"];

but i cannot use to create a NSFetchRequestController (this code use MagicalRecord)

NSFetchedResultsController *acontroller = [Customer fetchAllSortedBy:@"mainAddress.city" ascending:ascending withPredicate:companyPredicate groupBy:nil delegate:self];

This is the error:

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath mainAddress.city not found in entity <NSSQLEntity Customer id=4>'

Solution

  • In order to use the sorting with an NSFetchedResultsController, your mainAddress keyPath needs to be an attribute on your entity. NSFRC will sort the data not using KVC in memory, but using the underlying data store. Bottom line answer: make mainAddress a field on your entity in the data model.