Search code examples
iosxcode4ios4

How to split up pList alphabetically into groups like iOS contacts


I have been trying to separate a pList that I have already alphabetized into the TableView. For example, when the names switch from A to B, I want the fancy grouped table format to separate A from B.

Any ideas on how to do that?

Here is my code, that I have doing the sorting.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:kEMPLOYEE_PLIST];

NSMutableArray *countries = [[NSMutableArray alloc ]initWithContentsOfFile:path];

// Now the array holds NSDictionaries, sort 'em:
NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"FullName" ascending:YES] autorelease];
sortedCountries = [[countries sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]] retain];

Solution

  • Check out this potentially related question, but basically what you need to do is have each letter (or group) be a section.

    First you'll need to specify your table is grouped (whether in Interface Builder or via UITableView's - (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style method, specifying UITableViewStyleGrouped as the style.

    Then you'll want to implement:

    UITableViewDataSource's

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView method

    and

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

    and of course UITableViewDataSource's

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method.

    In this last method, you can look at indexPath.section to get the letter of the alphabet you want to return and indexPath.row to return the Nth entry that exists for that letter (group).

    Is this enough to work with for now?