Ios UITableView按核心数据划分的节和索引

Ios UITableView按核心数据划分的节和索引,ios,objective-c,uitableview,Ios,Objective C,Uitableview,我使用下面的代码通过“联系人”实体绑定tableview单元格 现在我想通过“联系人”实体中“姓名”字段的第一个字母向mytableview添加索引和节,请根据我的代码填写答案,谢谢你需要为UITableView实现以下数据源方法: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath - (NSInteger)tableView:(UITabl

我使用下面的代码通过“联系人”实体绑定tableview单元格


现在我想通过“联系人”实体中“姓名”字段的第一个字母向mytableview添加索引和节,请根据我的代码填写答案,谢谢你需要为UITableView实现以下数据源方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
前两个是标准的,实现将在表视图中显示的单元格

第三个是表视图应划分的节数。对于类似的内容,我将使用“字母表数组”,即包含字母表中所有字母的数组,例如:

NSMutableArray *alphabetArray = [[NSMutableArray alloc] init];
for (int i = 0; i < 26; i++) {
    char letter = 'A';
    letter += i;
    [alphabetArray addObject:[NSString stringWithFormat:@"%c", letter]];
}
您可以应用相同的逻辑使联系人显示在单元格中:

NSString *letter = alphabetArray[indexPath.section];
NSArray *filteredContacts = [contacts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", letter]];
Contact *contact = filteredContacts[indexPath.row];

希望这能有所帮助。

谢谢,但我该在哪里写呢?NSString*letter=alphabetArray[indexPath.section];NSArray*filteredContacts=[contacts FilteredArrayingPredicate:[NSPredicate Predicate WithFormat:@“名称以[cd]]@,字母]]开头];返回filteredContacts.count;好的,首先请格式化你的代码,否则它会变得难以阅读。您将该代码放在
-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)节中
。这个方法想知道在一个特定的部分中有多少行。因此,您需要获得所有以适当字母开头的联系人,并返回其号码。阅读
NSString *letter = alphabetArray[indexPath.section];
NSArray *filteredContacts = [contacts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", letter]];
return filteredContacts.count;
NSString *letter = alphabetArray[indexPath.section];
NSArray *filteredContacts = [contacts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", letter]];
Contact *contact = filteredContacts[indexPath.row];