简体   繁体   中英

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

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

NSSortDescriptor is overkill to sort an array whose elements are just NSString instances.

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:

[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. If that's the case, and the elements are just instances of NSString , @iHS's answer would be correct.

You can use NSSortDescriptor class for sorting purposes

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

For More information, have a look at

1) NSSortDescriptor

2) Sorting-NSArrays

you can use sortDescriptor

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

Swift 3.0:

categories is an array of 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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