我有一个数组:
NSArray *nameArray = [NSArray arrayWithObjects:
//A
@"Alpha",@"Ar",@"Ax",
//B
@"B", ... nil];
在我的viewDidLoad中,我执行以下操作:
_sectionedNameArray = [self partitionObjects:nameArray collationStringSelector:@selector(self)];
这是partitionObjects方法:
-(NSArray *)partitionObjects:(NSArray *)array collationStringSelector:(SEL)selector
{
_collation = [UILocalizedIndexedCollation currentCollation];
NSInteger sectionCount = [[_collation sectionTitles] count]; //section count is take from sectionTitles and not sectionIndexTitles
NSMutableArray *unsortedSections = [NSMutableArray arrayWithCapacity:sectionCount];
//create an array to hold the data for each section
for(int i = 0; i < sectionCount; i++)
{
[unsortedSections addObject:[NSMutableArray array]];
}
//put each object into a section
for (id object in array)
{
NSInteger index = [_collation sectionForObject:object collationStringSelector:selector];
[[unsortedSections objectAtIndex:index] addObject:object];
}
NSMutableArray *sections = [NSMutableArray arrayWithCapacity:sectionCount];
//sort each section
for (NSMutableArray *section in unsortedSections)
{
[sections addObject:[_collation sortedArrayFromArray:section collationStringSelector:selector]];
}
return sections;
}
以及以下内容:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[_sectionedNameArray objectAtIndex:section] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[_collation sectionTitles] objectAtIndex:section];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [_collation sectionIndexTitles];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}
这些部分无法正常工作。对于“A”部分,我得到“A”,然后为其他部分随机划分“A”。看起来每个部分都是从数组的开头算起来的......任何想法我的代码有什么问题?
更新以下评论来自rmaddy:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"hCell";
NameCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.hNameLabel.text = [nameArray objectAtIndex:indexPath.row];
cell.hCityLabel.text = [cityArray objectAtIndex:indexPath.row];
cell.hPoneLabel.text = [phoneArray objectAtIndex:indexPath.row];
return cell;
}