2

I have a UITableView which is populated with an array of objects of type 'Product' which each have a 'name' attribute of type string. When a cell is clicked, a modal view is shown with more information on that product.

What I would like to do is split the products up into sections depending on the first letter of their name attribute. (Like iPhone contacts).

I have been struggling with this for a while now, and I can't seem to find anything online that solves my particular problem..

Could someone point me in the right direction?

Meet Doshi
  • 4,241
  • 10
  • 40
  • 81
Jack Nutkins
  • 1,555
  • 5
  • 36
  • 71

2 Answers2

5

There are several good examples here on SO. Here is a good example:

How to sort an NSMutableArray with custom objects in it?

Community
  • 1
  • 1
dtuckernet
  • 7,817
  • 5
  • 39
  • 54
  • Thanks, that has shown me how to order the array alphabetically, but I'm still struggling to display the now organised array in a UITableView with alphabetical sections? – Jack Nutkins Jan 12 '12 at 05:22
  • If you implement the UITableViewDataSource protocol, you can define the number of rows / sections and what cell shows up at each point. You would use this sorted array to know what to present. You can see the protocol here: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewDataSource_Protocol/Reference/Reference.html – dtuckernet Jan 12 '12 at 19:25
  • In addition, if you want the alphabetical index - see the answer here: http://stackoverflow.com/questions/1655119/iphone-uitableview-how-do-turn-on-the-single-letter-alphabetical-list-like-the – dtuckernet Jan 12 '12 at 19:26
3

Use NSSortDescriptor like this..

NSSortDescriptor *sortDescriptor =
    [NSSortDescriptor sortDescriptorWithKey:@"name"
                                  ascending:YES
                                   selector:@selector(caseInsensitiveCompare:)];
NSArray *sortedArray = [nameOfArray sortedArrayUsingDescriptors:@[sortDescriptor]];

Hope, this is what you're looking for. Any concern get back to me. :)

Meet Doshi
  • 4,241
  • 10
  • 40
  • 81