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

问题描述:

我有一个NSMutableArray中的字符串列表,我想按字母顺序排列它们,然后将它们显示在我的表格视图中。如何将NSMutableArray中的字符串按字母顺序排序?

我该怎么做?

有下列苹果的工作例如,在使用Collections DocumentationsortedArrayUsingSelector:localizedCaseInsensitiveCompare:

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

注意这将返回一个新的排序的数组。如果你想在地方你NSMutableArray进行排序,然后用sortUsingSelector:代替,就像这样:

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

下面是斯威夫特更新的答案:

  • 排序可以在斯威夫特完成的帮助的关闭。有两种方法 - sortsorted,这有助于此。

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

    注意:这里sorted将返回一个排序后的数组。 unsortedArray本身不会被排序。

  • 如果要排序unsortedArray本身,使用此

    ​​


参考:

  • Here是斯威夫特的排序方法的文档。

  • Docs for different String比较方法here


可选

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

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

甚至

stringArray.sort{ $0 < $1 } 

我F你想有一个区分大小写的比较

+0

谢谢,'.lowercaseString'在比较对象与标题时为我完成了这项工作。 'mediaItems = mediaItems.sorted {$ 0.media.title.lowercaseString> $ 1.media.title.lowercaseString}' – 2015-08-25 11:22:41

对于我这种工作....

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

这方面是NSArray。我希望它能帮助别人。

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

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