How to reorder NSArray elements (NSString) in alphabetical order?

How to reorder NSArray elements (NSString) in alphabetical order?

+4
source share
5 answers

you can use sortDescriptor

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

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

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

If instead of a new array created with its sorted elements, you want the elements of the NSMutableArray instance to be reordered, there is a way to do this:

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

Use an instance of NSSortDescriptor when you have a large object that manages the array for you, such as NSArrayController or NSTableView. If this is the case, and the elements are just instances of NSString , @iHS answer will be correct.

+5
source

You can use the NSSortDescriptor class for sorting purposes.

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

For more information, browse

1) NSSortDescriptor

2) Sorting-NSArrays

+4
source

Of course you can do it. Try using NSSortDescriptor to get help from the one already set. Display data in alphabetical order iphone

0
source

Swift 3.0:

Categories

is an array of the category → [Category].

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

Replace the category with your custom array of objects. If you are using a regular NSArray, replace (categories as NSArray) with your array.

0
source

Source: https://habr.com/ru/post/1341642/


All Articles