"arr" here contains all the results obtained from the database or after parsing xml or any other.
Just sort the array in ascending order (arrSortedResults in my code).
- (void)viewDidLoad { [super viewDidLoad]; NSMutableArray *arr=[[NSMutableArray alloc]initWithObjects:@"a",@"b",@"c",@"c",@"a1",@"b1",@"c1",@"a2",@"a3",@"a4",@"b", nil]; tableGroupView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStyleGrouped];//simply initialization of tableview tableGroupView.delegate=self; tableGroupView.dataSource=self; [self.view addSubview:tableGroupView]; NSArray *arrSortedResults= [arr sortedArrayUsingSelector:@selector(compare:)]; ArrayForArrays=[[NSMutableArray alloc]init];//initialize a array to hold arrays for section of table view BOOL checkValueAtIndex=NO; //flag to check SectionHeadsKeys=[[NSMutableArray alloc]initWithObjects:nil];//initialize a array to hold keys like A,B,C ... for(int index=0;index<[arrSortedResults count];index++) { NSMutableString *strchar=[arrSortedResults objectAtIndex:index]; NSString *sr=[strchar substringToIndex:1]; NSLog(@"%@",sr);//sr containing here the first character of each string if(![SectionHeadsKeys containsObject:[sr uppercaseString]])//here I'm checking whether the character already in the selection header keys or not { [SectionHeadsKeys addObject:[sr uppercaseString]]; TempArrForGrouping=[[NSMutableArray alloc]initWithObjects:nil]; checkValueAtIndex=NO; } if([SectionHeadsKeys containsObject:[sr uppercaseString]]) { [TempArrForGrouping addObject:[arrSortedResults objectAtIndex:index]]; if(checkValueAtIndex==NO) { [ArrayForArrays addObject:TempArrForGrouping]; checkValueAtIndex=YES; } } } } //after this ArrayForArrays will contain all the arrays which will become groups under the header headerkeys - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return [ArrayForArrays count]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return [SectionHeadsKeys objectAtIndex:section]; } - (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section { NSArray *arr= [ArrayForArrays objectAtIndex:section]; return [arr count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier]; if(cell == nil) { cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier]; } int section=[indexPath section]; NSArray *arr=[ArrayForArrays objectAtIndex:section]; cell.textLabel.text=[arr objectAtIndex:indexPath.row]; return cell; } now output will be as bellow: ![enter image description here][1] [1]: http://i.stack.imgur.com/tcPr6.png
source share