iphone - NSArray 排序和隔离

标签 iphone uitableview sorting nsmutablearray nsarray

我有一个 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/

相关文章:

iphone - View 更改后动画不会重新启动

iphone - AVAudioSession endInterruption() 返回 NSOSStatusErrorDomain

ios - 如何segue UIImage?

iphone - 刷新 didSelectRowAtIndexPath 委托(delegate)上的 viewForFooterInSection

ios - 如何截断 UITableView Cell TextLabel 中的文本,使其不隐藏 DetailTextLabel?

javascript - 根据用户输入更新数组排序顺序

python - 根据两个元素对元组列表进行排序

iphone - 当 iOS 应用程序进入后台时,长时间的任务是否会暂停?

algorithm - 关于 Fast 3 Way Partition/in place quicksort via Sedgewick 中的排序数据

iphone - SKPSMTP消息设置WatchdogTimer :]: message sent to deallocated instance