user1033619
user1033619

Reputation: 1797

Objective-c: how to sort a NSMutableArray of UIButtons using their tags

I have a NSMutableArray containing UIButtons. I have given each of the buttons a unique tag. The buttons will be added to the array in random order, but i want to later sort it so that the buttons are in ascending order with respect to their tags.

Thanks for the help!

Upvotes: 0

Views: 892

Answers (3)

Hot Licks
Hot Licks

Reputation: 47729

There are multiple "sortedArrayUsing..." functions. Use the one that seems to fit your needs the best.

(BTW, remember that, since NSMutableArray is a subclass of NSArray, all of the methods of NSArray apply to NSMutableArray as well.)

Upvotes: 1

Yannick Reifschneider
Yannick Reifschneider

Reputation: 454

You can use the NSSortDescriptor to sort a NSArray.

NSArray *unsortedArray = ...
NSArray *sortedArray = [unsortedArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"tag" ascending:YES]]];

Upvotes: 2

Sr.Richie
Sr.Richie

Reputation: 5740

Yeap.

Try this:

NSSortDescriptor *ascendingSort = [[NSSortDescriptor alloc] initWithKey:@"tag" ascending:YES];
NSSortDescriptor *descendingSort = [[NSSortDescriptor alloc] initWithKey:@"tag" ascending:NO];
NSArray *sortedArray = [someArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:ascendingSort]];

Upvotes: 6

Related Questions