开发者

sorting array in tableview

开发者 https://www.devze.com 2023-02-19 19:50 出处:网络
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 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:

  • D
  • A
  • G
  • F
  • S

but listed like this instead:

  • A
  • B
  • C
  • D
  • E
  • Etc...

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 objec开发者_如何学编程tAtIndex:indexPath.row];
cell.textLabel.text = cellValue;


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];
}


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号