我有一个 NSArray 名称,我想将它们按字母顺序排序到 UITableView 中并将它们分成几个部分。
我在顶部有一个标记部分,即第 0 部分。我希望名称按字母顺序排序在后面。因此,所有以 A 开头的名称都会放入第 1 部分,B 会放入第 2 部分,依此类推。
我需要能够以某种方式获取每个部分的行数,然后将对象放入每个部分。
我该怎么做?
最佳答案
下面是 NSArray 上的类别进行分组的方法:
@interface NSArray (Grouping)
- (NSArray*) groupUsingFunction: (id (*)(id, void*)) function context: (void*) context;
@end
@implementation NSArray (Grouping)
- (NSArray*) groupUsingFunction: (id (*)(id, void*)) function context: (void*) context
{
NSArray* groupedArray = nil;
NSMutableDictionary* dictionary = [NSMutableDictionary new];
if (dictionary != nil)
{
for (id item in self)
{
id key = function(item, context);
if (key != nil)
{
NSMutableArray* array = [dictionary objectForKey: key];
if (array == nil) {
array = [NSMutableArray arrayWithObject: item];
if (array != nil) {
[dictionary setObject: array forKey: key];
}
} else {
[array addObject: item];
}
}
}
groupedArray = [NSMutableArray arrayWithArray: [dictionary allValues]];
[dictionary release];
}
return groupedArray;
}
@end
你可以像这样使用它:
id GroupNameByFirstLetter(NSString* object, void* context)
{
return [object substringToIndex: 1];
}
NSInteger SortGroupedNamesByFirstLetter(id left, id right, void* context)
{
return [[left objectAtIndex: 0] characterAtIndex: 0] - [[right objectAtIndex: 0] characterAtIndex: 0];
}
NSMutableArray* names = [NSArray arrayWithObjects: @"Stefan", @"John", @"Alex",
@"Sue", @"Aura", @"Mikki", @"Michael", @"Joe", @"Steve", @"Mac", @"Fred",
@"Faye", @"Paul", nil];
// Group the names and then sort the groups and the contents of the groups.
groupedNames_ = [[names groupUsingFunction: GroupNameByFirstLetter context: nil] retain];
[groupedNames_ sortUsingFunction: SortGroupedNamesByFirstLetter context: nil];
for (NSUInteger i = 0; i < [groupedNames_ count]; i++) {
[[groupedNames_ objectAtIndex: i] sortUsingSelector: @selector(compare:)];
}
关于iphone - NSArray 排序和隔离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2127315/