如何将NSMutableArray中的字符串按字母顺序排序?
答
有下列苹果的工作例如,在使用Collections Documentation和sortedArrayUsingSelector:
localizedCaseInsensitiveCompare:
:
sortedArray = [anArray sortedArrayUsingSelector:
@selector(localizedCaseInsensitiveCompare:)];
注意这将返回一个新的排序的数组。如果你想在地方你NSMutableArray
进行排序,然后用sortUsingSelector:
代替,就像这样:
[mutableArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
答
参考:
下面是斯威夫特更新的答案:
-
排序可以在斯威夫特完成的帮助的关闭。有两种方法 -
sort
和sorted
,这有助于此。var unsortedArray = [ "H", "ello", "Wo", "rl", "d"] var sortedArray = unsortedArray.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
注意:这里
sorted
将返回一个排序后的数组。unsortedArray
本身不会被排序。 -
如果要排序
unsortedArray
本身,使用此
参考:
可选:
而不是使用localizedCaseInsensitiveCompare
,这也可以这样做:
stringArray.sort{ $0.lowercaseString < $1.lowercaseString }
甚至
stringArray.sort{ $0 < $1 }
我F你想有一个区分大小写的比较
答
对于我这种工作....
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]];
谢谢,'.lowercaseString'在比较对象与标题时为我完成了这项工作。 'mediaItems = mediaItems.sorted {$ 0.media.title.lowercaseString> $ 1.media.title.lowercaseString}' – 2015-08-25 11:22:41