1

I can't figure how to sort data in UITableView alphabetically.

I've been using the ToDoList sample in Icodeblog (Website). Once I enter the data it appears on the UITableview. The data is located in a sqlite file.

I created a button in the UITableview bar to run this code to sort the text alphabetically... but it doesn't work:

    NSMutableArray *array = [NSMutableArray array];
    NSArray *sortedArray;
    NSSortDescriptor *lastDescriptor =
    [[NSSortDescriptor alloc] initWithKey:newTodo.text
                                ascending:YES
                                 selector:@selector(localizedCaseInsensitiveCompare:)];
    NSArray *descriptors = [NSArray arrayWithObjects:lastDescriptor, nil];
sortedArray = [array sortedArrayUsingDescriptors:descriptors];
    [self.tableView reloadData];

Please point me to the right direction. My friend also told me to check "sortUsingSelector" method ... but I still can't figure it out.

The sample code that I'm using is located here.

MichaelD
  • 31
  • 1
  • 6

3 Answers3

1

Just tested the sample code, this is what I did to it. NSSortDescriptor will use KVC, so the initWithKey will be corresponding property from the object. Your code doesn't do anything at the moment, you're trying to sort an empty array. Additionally, you're not modifying your table view data source.

- (void)viewWillAppear:(BOOL)animated 
{
    todoAppDelegate *appDelegate = (todoAppDelegate *)[[UIApplication sharedApplication] delegate];
    NSSortDescriptor *lastDescriptor =
    [[NSSortDescriptor alloc] initWithKey:@"text"
                                ascending:YES
                                 selector:@selector(localizedCaseInsensitiveCompare:)];
    NSArray *descriptors = [NSArray arrayWithObjects:lastDescriptor, nil];
    NSMutableArray* sortedArray = [[[appDelegate.todos sortedArrayUsingDescriptors:descriptors] mutableCopy] autorelease];
    appDelegate.todos = sortedArray;

    [self.tableView reloadData];
    [super viewWillAppear:animated];
}
X Slash
  • 4,133
  • 4
  • 27
  • 35
0

Take a look at :

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Collections/Articles/Arrays.html#//apple_ref/doc/uid/20000132-SW5

sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

As in this question :

How to sort a NSArray alphabetically?

localizedCaseInsensitiveCompare is a method of NSString class

Community
  • 1
  • 1
ant
  • 22,634
  • 36
  • 132
  • 182
0

You can get along with the answers these guys put on here but for the sake of simplicity I would do the sorting with the help of query like:

 "SELECT * FROM <table-name> ORDER BY <column-name>"

That could be a simpler way I guess.

Ahmed
  • 772
  • 1
  • 9
  • 26