我有一个名称数组,我想将节头作为字母表,如A B C。还有索引。从名称数组中生成Section的最有效方法是什么?
以下是我开发的方法,该方法在NSArray
上进行处理并创建了您所关注的NSDictionary
。
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray* internalArray = [NSMutableArray arrayWithObjects:@"abc",@"xyz",@"aa",@"bb", nil];
NSDictionary* dictStructued = [self sortArrayAndMakeStructur:internalArray];
NSLog(@"Output : %@",dictStructued.description);
}
这是你的全部方法。。
-(NSMutableDictionary*)sortArrayAndMakeStructur:(NSArray*)array{
NSMutableDictionary* dictIndexes = [[NSMutableDictionary alloc]init];
NSArray* sortedArray = [array sortedArrayUsingSelector:
@selector(localizedCaseInsensitiveCompare:)];
for (int i=0; i<[sortedArray count]; i++) {
NSString* strName = sortedArray[i];
if ([[dictIndexes allKeys] containsObject:[[strName substringToIndex:1] uppercaseString]]) {
NSMutableArray* internalArray = [NSMutableArray arrayWithArray:[dictIndexes valueForKey:[[strName substringToIndex:1] uppercaseString]]];
[internalArray addObject:strName];
[dictIndexes setObject:internalArray forKey:[[strName substringToIndex:1] uppercaseString]];
}
else{
NSMutableArray* internalArray = [NSMutableArray arrayWithObjects:strName, nil];
[dictIndexes setObject:internalArray forKey:[[strName substringToIndex:1] uppercaseString]];
}
}
return dictIndexes;
}
此处节计数=[[dictStructued allKeys] count];
行数=[[dictIndexes valueForKey:yourKey] count];
输出:
{
A = (
aa,
abc
);
B = (
bb
);
X = (
xyz
);
}
请使用嵌套的NSArray或每个键都有数组的NSDictionary。
引用自:http://www.appcoda.com/ios-programming-index-list-uitableview/
首先,我们用字母表对它们进行排序:
NSMuatableArray* sortedArray = [anArray sortedArrayUsingSelector:
@selector(localizedCaseInsensitiveCompare:)];
我们在- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
中正常填充
希望这能有所帮助。