views:

117

answers:

2

I have this set

NSMutableSet *mySet = [NSMutableSet setWithObjects: @"2", @"8", @"7", @"0", @"3", nil];

I copy the set to an array and sort it using

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

The resulting array is in exactly the same order as the set and is not being sorted. Why?

thanks for any help.

EDIT: CORRECTING A TYPO.

+3  A: 

Uhm, it correctly sorts, once I corrected the set construction to

NSMutableSet *mySet = [NSMutableSet setWithObjects: @"2", @"8", @"7", @"0", @"3", nil];

Remember, "abc" is a char*, which is a primitive type which you rarely use in Objective-C, and you can't put it in NSArray. @"abc" is the NSString, which is an object.

Yuji
Sorry about that. It was a typo in my code here on SO. My code has the @... and is not sorting.
Digital Robot
Well it correctly sorted in my Mac. How did you check the result? Your code doesn't sort `mySet`. Your code just store the sorted result in `sortedArray`. Did you `NSLog` `sortedArray` or `mySet`?
Yuji
You *can't* sort `mySet`, or any other set. He says in a comment on TechZen's answer that he did, in fact, log the set instead of the sorted array.
Peter Hosey
+2  A: 

I pasted and ran you code like this:

NSMutableSet *mySet = [NSMutableSet setWithObjects: @"2", @"8", @"7", @"0", @"3", nil];
NSLog(@"mySet=%@",mySet);
NSArray *sortedArray = [[mySet allObjects] sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"sortedArray=%@",sortedArray);

Which outputs:

2010-03-17 11:06:27.982 iPhoneTestBed[41907:207] mySet={(
    0,
    2,
    7,
    8,
    3
)}
2010-03-17 11:06:27.984 iPhoneTestBed[41907:207] sortedArray=(
    0,
    2,
    3,
    7,
    8
)

I think your problem is with your logging of the sorted array. Perhaps you're accidentally logging the set instead of the array. I wasted half a day once doing that.

TechZen