开发者

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

Ho开发者_运维技巧w to reorder elements (NSString) of an NSArray alphabetically?


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 sortDescriptor

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


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


Sure you can do it Try Using NSSortDescriptor take help from already ask Display data in alphabetical order iphone


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜