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

42
我有一个字符串列表在NSMutableArray中,并且我想在将它们显示在我的表视图之前按字母顺序排序它们。
我该如何做呢?
4个回答

128

以下是苹果官方文档中的示例,使用 sortedArrayUsingSelector:localizedCaseInsensitiveCompare:集合文档 中进行排序:

sortedArray = [anArray sortedArrayUsingSelector:
                       @selector(localizedCaseInsensitiveCompare:)];
请注意,这将返回一个新的排序数组。如果您想原地排序您的NSMutableArray,则使用sortUsingSelector:,像这样:
[mutableArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

8

以下是有关 Swift 的更新答案:

  • Sorting can be done in Swift with the help of closures. There are two methods - sort and sorted which facilitate this.

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

    Note: Here sorted will return a sorted array. The unsortedArray itself will not be sorted.

  • If you want to sort unsortedArray itself, use this

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


参考:

  • 这里是Swift排序方法的文档。

  • 不同String比较方法的文档在这里


可选项:

除了使用localizedCaseInsensitiveCompare,也可以这样做:

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

甚至更多
stringArray.sort{ $0 < $1 }

如果你需要进行区分大小写的比较


谢谢,.lowercaseString 对于我使用标题比较对象很有用。 mediaItems = mediaItems.sorted { $0.media.title.lowercaseString > $1.media.title.lowercaseString } - Gerrit Post

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]];

0

对我来说,这个方法可行...

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

这里是 NSArray。希望能对某些人有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接