Search code examples
iosnssortdescriptor

Sort Fetch Resullts Controller based on Users Button Click IOS


I am making an Iphone app and am trying to perform a sort on my fetched results controller based on a user tapping a specific button. When the user clicks the button I put the code I have shown below, however I get an error saying

-[NSSortDescriptor count]: unrecognized selector sent to instance 0x6bc3250

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-. How can i fix this and get my data sorted based on the users button click?

- (IBAction)btnValue:(id)sender {
    self.model.frc_Work.delegate = self;

    self.model.frc_Work.fetchRequest.sortDescriptors = [NSSortDescriptor sortDescriptorWithKey:@"Value" ascending:YES];

    [NSFetchedResultsController deleteCacheWithName:@"Work"];

    NSError *error = nil;
    [self.model.frc_Work performFetch:&error];
}

Solution

  • You should be getting a compiler warning that you're assigning the wrong type of object to the sortDescriptors property of the fetch request, which expects an NSArray, not an NSSortDescriptor.

    You can assign it like this instead:

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"Value" ascending:YES];
    self.model.frc_Work.fetchRequest.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    

    The reason this property takes an array is so you can specify a list of sort descriptors to be applied in succession to values that may have the same value for certain keys (e.g. sort by last name, then by first name if the last names are equal).