How to sort tableview rows?

Hi

I completed Start Developing iOS Apps Today tutorial "ToDoList" and I implemented this tutorial app. Now I'm trying to sort the rows on tableview by an ascending key. Is it possible? How to sort mutablearray in this tutorial and fetch it to rows on tableview?

Sorting the data source and then triggering a reload of the tableview should be an option.

Here is how I do it with NSMutableArray objects when I need to sort ascending on a string property: (descending add ! after return before bracket: "return ![...")


NSMutableArray *dataToSort = [data mutableCopy];
[dataToSort sortUsingComparator:^NSComparisonResult(MyObject *obj1, MyObject *obj2) {
     return [obj1.aString localizedCompare:obj2.aString];
}];
data = dataToSort;
[self.tableView reloadData];
Accepted Answer

If your array contains NSDictionary objects, you can also sort by a specific object within the dictionary, e.g.:


NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"dictionaryKey1" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
self.tableData = [[self.tableData sortedArrayUsingDescriptors:sortDescriptors]mutableCopy];
[self.tableView reloadData];

I tried this and it doesn't work , output: unrecognized selector sent to instance 0x7f9773609ee0


It seems compare not the array's contents but an address...


@interface ListOfProductsTableViewController ()

@property NSMutableArray *products;

@end

@implementation ListOfProductsTableViewController



// When user taps A-z button sort list of products ascending

- (IBAction)Ordena:(UIBarButtonItem *)sender {


[self.produtos sortUsingSelector:@selector(caseInsensitiveCompare:)];

[self.tableView reloadData];

After hours (and days) reading guides manuals, etc. etc. I found the right way:


NSSortDescriptor *produtoDescriptor = [[NSSortDescriptor alloc]

initWithKey:@"itemName" ascending:YES selector:@selector(localizedStandardCompare:)];

NSArray *sortDescriptors = @[produtoDescriptor];

self.products = [[self.products sortedArrayUsingDescriptors:sortDescriptors]mutableCopy];

[self.tableView reloadData];


Thank You!

My advice :You'd better check the custome method named (LocalizedStandardCompare)

How to sort tableview rows?
 
 
Q