我有一個NSArray的名稱,我想按字母順序排列它們到一個UITableView中,並將它們分成多個部分。NSArray排序和隔離
我在頂部有一個標記的部分,是第0部分。我希望名稱排序後aplhabetically來。因此,所有以A開頭的名字都會放入第1部分,B會放入第2部分,依此類推。
我需要能夠以某種方式得到每個部分的行數,然後把每個部分的對象。
我該怎麼做?
我有一個NSArray的名稱,我想按字母順序排列它們到一個UITableView中,並將它們分成多個部分。NSArray排序和隔離
我在頂部有一個標記的部分,是第0部分。我希望名稱排序後aplhabetically來。因此,所有以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:)];
}
我修改St3fans回答是有點更現代和工作用塊來代替:
@interface NSArray (Grouping)
- (NSArray*) groupUsingBlock:(NSString* (^)(id object)) block;
@end
- (NSArray*) groupUsingBlock:(NSString* (^)(id object)) block
{
NSArray* groupedArray = nil;
NSMutableDictionary* dictionary = [NSMutableDictionary new];
if (dictionary != nil)
{
for (id item in self)
{
id key = block(item);
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;
}
您可以使用它像這樣:
NSArray *grouped = [arrayToGroup groupUsingBlock:^NSString *(id object) {
return [object valueForKey:@"name"];
}];