Alivajorg
Alivajorg

Reputation: 21

how to sort a tableview cell alphabetically

i have date view cell that is been filled by an array, i need to add two buttons one for A to Z and other Z to A. I able to sort the array but not sure how to change it in runtime i mean in the table view pressing the buttons. This is te code i using to sort:

[filePathsArray sortUsingSelector:@selector(compare:)];

The table view is just regular table view been filed with an array from a csv file. This is how i get the array paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSFileManager *manager = [NSFileManager defaultManager];
NSMutableArray*   fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
//--- Listing file by name sort
NSLog(@"\n File list %@",fileList);

//---- Sorting files by extension
NSMutableArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];

[filePathsArray sortUsingSelector:@selector(compare:)];
NSLog(@"\n sort by");

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF EndsWith '.csv'"];
filePathsArray =  [filePathsArray filteredArrayUsingPredicate:predicate];
NSLog(@"\n\n Sorted files by extension %@",filePathsArray);

any help or orientation would be appreciated. Thanks.

Upvotes: 0

Views: 140

Answers (1)

Gereon
Gereon

Reputation: 17844

Use sortUsingComparator instead of sortUsingSelector to implement the different sorting directions:

[filePathsArray sortUsingComparator:^NSComparisonResult(NSString* fp1, NSString* fp2) {
  return [fp1 compare:fp2];
}];

and to revert the sort direction, simply swap the parameters for compare:

[filePathsArray sortUsingComparator:^NSComparisonResult(NSString* fp1, NSString* fp2) {
  return [fp2 compare:fp1];
}];

Your A-Z and Z-A buttons can then simply sort using one of those methods and call [tableView reloadData].

Upvotes: 1

Related Questions