如何将NSMutableArray中的字符串排序为字母顺序?

时间:2011-06-11 10:15:26

标签: objective-c ios cocoa-touch sorting nsmutablearray

我在NSMutableArray中有一个字符串列表,我想在按表格视图显示之前将它们按字母顺序排序。

我该怎么做?

4 个答案:

答案 0 :(得分:128)

sortedArrayUsingSelector:中使用localizedCaseInsensitiveCompare:Collections Documentation,有以下Apple的工作示例:

sortedArray = [anArray sortedArrayUsingSelector:
                       @selector(localizedCaseInsensitiveCompare:)];

请注意,这将返回一个新的已排序数组。如果您想对NSMutableArray进行排序,请改用sortUsingSelector:,如下所示:

[mutableArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

答案 1 :(得分:8)

这是 Swift 的更新答案:

  • 可以在闭包的帮助下在Swift中完成排序。有两种方法 - sortsorted可以促进这一点。

    var unsortedArray = [ "H", "ello", "Wo", "rl", "d"]
    var sortedArray = unsortedArray.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
    

    注意:此处sorted将返回已排序的数组。 unsortedArray本身不会被排序。

  • 如果您想对unsortedArray本身进行排序,请使用此

    unsortedArray.sort { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
    

<小时/> 参考:

  • Here是Swift排序方法的文档。

  • 不同String比较方法here的文档。


<强>可选

不是使用localizedCaseInsensitiveCompare,也可以这样做:

stringArray.sort{ $0.lowercaseString < $1.lowercaseString }

甚至

stringArray.sort{ $0 < $1 }

如果您想要区分大小写的比较

答案 2 :(得分:1)

升序很容易。按照下面的步骤,,,

模型1:

NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
sortedArray=[yourArray sortedArrayUsingDescriptors:@[sortDesc]];

如果您希望排序不区分大小写,则需要像这样设置描述符 模型2:

NSSortDescriptor * sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)]; 
sortedArray=[yourArray sortedArrayUsingDescriptors:@[sortDesc]];

答案 3 :(得分:0)

对我来说这很有用......

areas = [areas sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

此处的区域为NSArray。我希望它有所帮助。

相关问题