2013-07-14 32 views
2

我正在製作帶有表格視圖的應用程序,並且希望能夠對錶格數據進行排序,如本地聯繫人應用程序,其中名稱的第一個字母是用所有具有相同首字母的其他名稱排序。我使用了一個可變數組。如何在表格視圖中將數組按字母順序排列組織

下面是在實現文件表中的代碼(這是不是從文件中的所有代碼,只是在表的它的部分):

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 


    self.doctorNames = [NSMutableArray.alloc 
         initWithObjects:@"Aaron Smith", @"Michael Jordan", @"Cormac Chester", @"Marcus Baloutine", @"Joe Schmo", @"Sly James", @"Barack Obama", @"Joe Biden", @"Superman", @"Batman", @"Robin", @"Commissioner Gorden", @"Joseph Gordon Levitt" ,nil]; 
} 

- (NSInteger)tableView:(UITableView *)tableView 
numberOfRowsInSection:(NSInteger)section 
{ 
    if(tableView == self.searchDisplayController.searchResultsTableView) 
    { 
     return [searchResults count]; 
    } 
    else 
    { 
     return [self.doctorNames count]; 
    } 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) 
    { 
     cell = [UITableViewCell.alloc 
       initWithStyle:UITableViewCellStyleDefault 
       reuseIdentifier:CellIdentifier]; 
    } 
    if (tableView == self.searchDisplayController.searchResultsTableView) 
    { 
     cell.textLabel.text = [searchResults objectAtIndex:indexPath.row]; 
    } 
    else 
    { 
     cell.textLabel.text = [doctorNames objectAtIndex:indexPath.row]; 
    } 


    return cell; 
} 

-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope 
{ 
    NSPredicate*resultPredicate =[NSPredicate predicateWithFormat:@"SELF contains[cd] %@", searchText]; 
    searchResults =[doctorNames filteredArrayUsingPredicate:resultPredicate]; 
} 


-(BOOL)searchDisplayController:(UISearchDisplayController *)controller 
shouldReloadTableForSearchString:(NSString*)searchString 
{ 
    [self filterContentForSearchText:searchString 
    scope:[[self.searchDisplayController.searchBar scopeButtonTitles] 
    objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; 

    return YES; 
} 

回答

1

你可以用它來按字母順序排列陣列:

[self.doctorNames sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 
+0

這不提供足夠的信息來顯示錶視圖中的多個部分。 – rmaddy

2

您的數據結構安裝不正確。你想要一個節數據數組。數組中的每個元素都應該是一個字典。每個字典都應該有一個關鍵部分的標題和一個關鍵部分的行。

擁有一個大數組不適合分區表。