Search code examples
iossortingcore-datanstableviewnsarraycontroller

how to sort a view-based tableview


I can't manage to sort a view-based tableview. I use an arrayController that control an entity of core data.

I tried to select a column and in the attribute inspector I used as a sort key the attributes name relative to that column and compare: as a selector... when I build and run I click on the header and now display the arrow that change every click, but the nothing happens with the rows. no sorting.

How can I fix it?
I think I'm missing something easy, but I can't get over it.


Solution

  • You may want to consider using an NSFetchedResultsController. From the Apple documentation for NSFetchedResultsController,

    You use a fetched results controller to efficiently manage the results returned from a Core Data fetch request to provide data for a UITableView object.

    The code looks like this where the line that provides the sort descriptor starts with NSSortDescriptor.

    - (NSFetchedResultsController *)fetchedResultsController
    {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"YourEntityName"
                                                  inManagedObjectContext:yourManagedObjectContext];
        [fetchRequest setEntity:entity];
    
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"YourSortKey"
                                                                       ascending:YES];
    
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
        [fetchRequest setSortDescriptors:sortDescriptors];
    
        NSError *error = nil;
        NSArray *fetchedObjects = [yourManagedObjectContext executeFetchRequest:fetchRequest 
                                                                          error:&error];
        if (fetchedObjects == nil) {
            // Handle the error
        }
    
        yourFetchedResultsController = [[NSFetchedResultsController alloc] 
                initWithFetchRequest:fetchRequest 
                managedObjectContext:self.managedObjectContext
                  sectionNameKeyPath:nil
                           cacheName:nil];
    
        return yourFetchedResultsController;
    }