Search code examples
cocoacore-datansarraycontroller

Having Trouble Sorting CoreData backed NSArrayController


Im trying to retrieve an array of sorted objects from my Core Data backed NSArrayController. Once the ManagedObjectContext is ready I fire a Notification which the object owning the NSArrayController listens for and then sets up the fetch request with sortDescriptors. However the data is NEVER sorted. I've been pounding my head on this for several hours now.

I get the expected data in the array but it's not sorted at all. Anyone have any ideas where I am going wrong?

// Elsewhere in code
...
_charts = [[NSArrayController alloc] init];
_charts.entityName = @"Charts";
...

// When Cored Data and Managed Object Context is ready
-(void)mangagedObjectContextReady
{
    NSManagedObjectContext *moc = ((AppDelegate *)[NSApp delegate]).managedObjectContext;
    _charts.managedObjectContext = moc;
    _charts.usesLazyFetching = NO;
    _charts.automaticallyPreparesContent = YES;
    _charts.automaticallyRearrangesObjects = YES;

    // Create fetch request for data
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    fetchRequest.entity = [NSEntityDescription entityForName:@"Charts" inManagedObjectContext:moc];

    // Create the sort descriptors for the Charts entity
    // Name and chartType are properties on the entity "Charts"
    NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
    NSSortDescriptor *chartTypeDescriptor = [[NSSortDescriptor alloc] initWithKey:@"chartType" ascending:YES selector:@selector(caseInsensitiveCompare:)];
    fetchRequest.sortDescriptors = @[nameDescriptor, chartTypeDescriptor];

    NSError *error = nil;
    BOOL success = [_charts fetchWithRequest:fetchRequest merge:NO error:&error];
    if(!success)
        NSLog(@"Error %@:", [error localizedDescription]);
    else {
       [_charts rearrangeObjects];
       [_tv reloadData];
    }

I use this method to get an array or sorted objects.. but data is not sorted as per above sort descriptors?

[_charts.arrangedObjects objectAtIndex:row]

Solution

  • _charts.sortDescriptors = @[nameDescriptor, chartTypeDescriptor];