Search code examples
objective-cuitableviewuisegmentedcontrolnssortdescriptor

UITableView sort with NSSortDescriptor and UISegmentedControl doesn’t work


I want to sort my tableview by using a segmented control and sort it by a value from my datacore. According to Apple documentation my code below should work, but it doesn’t do anything.

Can anyone tell me what I am doing wrong?

- (void)viewDidLoad {
  [super viewDidLoad];

    UISegmentedControl *statFilter = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"A - Z", @"Stock", @"Price", nil]];
    [statFilter sizeToFit];
    [statFilter addTarget:self action:@selector(MySegmentControlAction:) forControlEvents: UIControlEventValueChanged];
    self.navigationItem.titleView = statFilter;

    self.artists = [[ArtistDataStore sharedStore] artists];
    [self.tableView reloadData];

    self.tableView.rowHeight = 60;

}


- (void)MySegmentControlAction:(UISegmentedControl *)segment
{
    NSArray *arrayToSort = [[ArtistDataStore sharedStore] artists];


    if(segment.selectedSegmentIndex == 0)
    {

        NSArray * result = [arrayToSort valueForKey:@"name"];

        NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
        result = [result sortedArrayUsingDescriptors:@[sd]];

    }
    if(segment.selectedSegmentIndex == 1)
    {
        NSArray * result = [arrayToSort valueForKey:@"stock"];

        NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
        result = [result sortedArrayUsingDescriptors:@[sd]];

    }
    if(segment.selectedSegmentIndex == 2)
    {
        NSArray * result = [arrayToSort valueForKey:@"price"];

        NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
        result = [result sortedArrayUsingDescriptors:@[sd]];

    }

    [self.tableView reloadData];
}

Solution

  • NSArray *arrayToSort = [[ArtistDataStore sharedStore] artists];
    NSString *key;
    if (segment.selectedSegmentIndex == 0)
    {
        key = @"name";
    }
    else if (segment.selectedSegmentIndex == 1)
    {
        key = @"stock";
    }
    else if (segment.selectedSegmentIndex == 2)
    {
        key = @"price";
    }
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:YES];
    self.artists = [arrayToSort sortedArrayUsingDescriptors:@[sortDescriptor]];
    
    [self.tableView reloadData];
    

    I assume when you configure your cells in tableView:cellForRowAtIndexPath: you use your self.artists array for the data. So in MySegmentControlAction: you should be updating that array instead of the results array that never actually gets used. You were also not setting up your sortDescriptor with a key. I have corrected it in the code above.

    This assumes that each member of the artists array has properties called 'name', 'stock' and 'price'.