Patrick R
Patrick R

Reputation: 1979

sorting array in tableview

I have an array and a tableview that gets its data from the array. When I view the tableview on the iPhone, its, ofc, not sorted, and its listed as I have written them.

I wanna sort my array in the tableview, so they aren't listed like this:

but listed like this instead:

How can I do this?

Here is my array:

stationList = [[NSMutableArray alloc] init];
[stationList addObject:@"A"];
[stationList addObject:@"B"];
[stationList addObject:@"C"];

How do I load the array into my tableview array? Loading the array:

NSString *cellValue = [stationList objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;

Upvotes: 0

Views: 3634

Answers (3)

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31722

Go to the below tutorial for sorting NSArray, they have explained the basic technique to sort a NSArray.

You can also download the sample code provided in the end of tutorial. Here is the link.

Upvotes: 2

ValayPatel
ValayPatel

Reputation: 1094

You can user some simple steps. Which I am using. I am not sure its perfect in context of memory consumption. But its working with me in my application.

Here record is NSMutableArray. Columnname is on Which Coulmn you want sorting. In my case I had more than one column to sort. And Sorting takes BOOL data.

After soring I am reloading my TableView.



    NSSortDescriptor * frequencyDescriptor = [[NSSortDescriptor alloc] initWithKey:columnName ascending:YES];

    NSArray * descriptors = [NSArray arrayWithObjects:frequencyDescriptor, nil];
    [record sortUsingDescriptors:descriptors];
    [columnName release];
    [frequencyDescriptor release];
    [myTableView reloadData];   



I hope this is fine. Do let me know if I can make it better

Upvotes: 0

Oliver
Oliver

Reputation: 23500

Use [stationList sortUsingFunction:compareLetters context:whateveryouwant_ornil]

And

NSComparisonResult compareLetters(id t1, id t2, void* context) {

      do the tests you want beetween t1 and t2, and return the result
      like :

      if (the test) return NSOrderedDescending, NSOrderedAscending or NSOrderedSame
}

In your example, you should do :

NSMutableArray stationList = [[NSMutableArray array];
[stationList addObject:@"A"];
[stationList addObject:@"B"];
[stationList addObject:@"C"];
[stationList sortUsingFunction:compareLetters context:nil];

NSComparisonResult compareLetters(id t1, id t2, void* context) {
      return [t1 compare:t2];
}

Upvotes: 4

Related Questions