按照iphone排序的地址簿排序NSSrings的NSArray

时间:2011-07-27 13:48:52

标签: iphone objective-c nsstring nsarray addressbook

我有一个字符串数组(名称)

我想对它们进行排序,就像iphone上的地址簿对它们进行排序一样

  • 例如:éli - >在E
  • 例如:àli - >在A
  • 例如:4li - >在#

有什么建议吗?

2 个答案:

答案 0 :(得分:11)

您需要对字符串执行变音符号不敏感的比较。 NSString有一个compare:options:方法,可选择NSDiacriticInsensitiveSearch

NSArray *array = [NSArray arrayWithObjects:@"éli", @"bob", @"earl", @"allen", @"àli", @"aaron", nil];

NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [(NSString*)obj1 compare:obj2 options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch];
}];

修改

这是一个完整的示例,它将基于第一个字符变音符号不敏感来划分结果。我输入了一本字典,因此你需要自己跟踪排序的键才能正确显示。

NSArray *array = [NSArray arrayWithObjects:@"éli", @"bob", @"earl", @"allen", @"àli", nil];

NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [(NSString*)obj1 compare:obj2 options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch];
}];

NSMutableDictionary *sectioned = [NSMutableDictionary dictionary];
NSString *firstChar = nil;

for(NSString *str in sorted)
{
    //Ignore empty strings
    if(![str length])continue;

    NSMutableArray *names = nil;

    //Compare the first character using diacritic insensitive search
    if([str compare:firstChar options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch range:NSMakeRange(0, 1)] == NSOrderedSame)
    {
        names = [sectioned objectForKey:firstChar];
    }
    else
    {
        //decomposedStringWithCanonicalMapping is where the magic happens
        //(it removes the accent mark)
        firstChar = [[str decomposedStringWithCanonicalMapping] substringToIndex:1];
        names = [NSMutableArray array];
        [sectioned setObject:names forKey:firstChar];
    }

    [names addObject:str];
}

NSLog(@"sorted: %@", sorted);
//This is sectioned like the address app
NSLog(@"sectioned: %@", sectioned);

答案 1 :(得分:1)

所有内容都在compare:方法中,您将用作排序方法的选择器,更重要的是使用NSDiacriticInsensitiveSearch选项。

[[yourArray] sortedArrayUsingSelector:@selector(compareTheAddressBookWay:)];

现在您需要在类别

中添加compareTheAddressBookWay:方法
@implementation NSString (YourCategory)

- (NSComparisonResult) compareTheAddressBookWay:(NSString*)iString
{
    return [self compare:iString 
                 options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch 
                   range:NSRangeFromString(self)
}

@end

!!重要!!:

使用sortedArrayUsingSelector:符合iOS 2.0标准
使用sortedArrayUsingComparator:适用于iOS 4及更高版本。