简体   繁体   English

如何按字母顺序重新排序NSArray的元素(NSString)?

[英]How to reorder elements (NSString) of an NSArray alphabetically?

如何按字母顺序重新排序NSArray的元素(NSString)?

NSSortDescriptor is overkill to sort an array whose elements are just NSString instances. NSSortDescriptor对于其元素只是NSString实例的数组进行排序是过分的。

NSArray *sortedArray = [unsortedArray sortedArrayUsingSelector: @selector(compare:)];

If, instead of a new array instantiated with its elements sorted, you want to have the elements of an NSMutableArray instance reordered, there's a method for that: 如果您希望重新排序NSMutableArray实例的元素而不是实例化其元素排序的新数组,那么有一种方法:

[unsortedMutableArray sortUsingSelector: @selector(compare:)];

Use an NSSortDescriptor instance when you have a large object managing the array for you, like an NSArrayController or an NSTableView. 当您有一个大型对象为您管理数组时,请使用NSSortDescriptor实例,如NSArrayController或NSTableView。 If that's the case, and the elements are just instances of NSString , @iHS's answer would be correct. 如果是这种情况,并且元素只是NSString的实例,那么@ iHS的答案是正确的。

You can use NSSortDescriptor class for sorting purposes 您可以使用NSSortDescriptor类进行排序

NSSortDescriptor * sortDesc = [[NSSortDescriptor alloc] initWithKey:@”self” ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
[sortDesc release];

For More information, have a look at 有关更多信息,请查看

1) NSSortDescriptor 1) NSSortDescriptor

2) Sorting-NSArrays 2) 排序-NSArrays

you can use sortDescriptor 你可以使用sortDescriptor

 NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"yourKey" ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
NSArray * sortedArray =
    [yourArray sortedArrayUsingDescriptors:descriptor];

Swift 3.0: Swift 3.0:

categories is an array of Category -> [Category]. categories是Category - > [Category]的数组。

let sortDescriptor = NSSortDescriptor(key: "name", ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))                                                  
let orderedCategories = (categories as NSArray).sortedArray(using: [sortDescriptor])

Replace category with your custom object array. 用您的自定义对象数组替换类别。 If you are using a regular NSArray, replace the (categories as NSArray) with your array. 如果您使用常规NSArray,请将(categories as NSArray)替换(categories as NSArray)您的阵列。

当然可以这样做尝试使用NSSortDescriptor从已经要求帮助显示按字母顺序iphone显示数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM