简体   繁体   中英

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!

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]];

You can use the NSSortDescriptor to sort a NSArray.

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

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.)

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