objective-c sort NSMutableSet of NSStrings? [duplicate]
Asked Answered
C

3

5

Possible Duplicate:
What is the most efficient way to sort an NSSet?

I currently have an NSMutableSet with the following a list of strings. e.g.: {@"c",@"d",@"e",@"f",@"g",@"a"}

Can someone please tell me how I can sort these values alphabetically? Is there a way to do this using sortedArrayUsingDescriptors: ?

Caston answered 22/12, 2011 at 19:36 Comment(3)
#1351682Bootstrap
The selector from the above post is available on NSSet. Note that it will no longer be a set. Arrays are ordered, sets are not.Bootstrap
I would say that this is not a dup of that question. Specifically, that other, more general question offers zero help on how to create the descriptor in this particular edge case, and it's not as obvious as it looks, because the first thing you think is, "but I don't want to sort based on a key on the object; I want to sort based on the object itself". Of course, the answer is that the "self" key gives that to you, but for people who don't know key-value coding backwards and forwards, it isn't particularly obvious. :-)Broughton
I
15

Sure, you can use that method:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES];
NSArray *sortedArray = [mySet sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];

This just creates a new sort descriptor that specifies the key "description" (NSString provides a -description method that returns the string). It then passes an array containing that sort descriptor as a parameter to -sortedArrayUsingDescriptors:, which you can send to any NSSet.

Interpolate answered 22/12, 2011 at 19:44 Comment(3)
If you pass "self" as the key, you get the same results. I think by requesting the description key, you're actually doing extra work. Specifically, I think it obtains the value to use for sorting by calling the description method on the value of the requested key, so you're actually taking the description of the description).Broughton
@Broughton you beat me to it. I just wrote some code to sort an array of NSStrings and decided to place @"self" for the key. Came here to check if there was an alternative.Valdavaldas
@Broughton You're not wrong, but using description Is a little more robust in that it works even if the array contains objects that aren't strings. Whether that's really desirable is a matter of opinion since OP did specify that the objects are strings, but at the same time the amount of extra work is negligible.Interpolate
R
1

I'm going to assume that this question Sorting NSSet is the answer to your very question. For the hard of clicking ...

[mySet sortedArrayUsingDescriptors:descriptors];
Ramp answered 22/12, 2011 at 19:40 Comment(0)
B
-2

NSSets are unordered collections. If you want a sorted container, use NSArray.

Bodine answered 22/12, 2011 at 19:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.