Duck
Duck

Reputation: 36003

Cocoa - array not sorting?

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.

Upvotes: 0

Views: 260

Answers (2)

TechZen
TechZen

Reputation: 64428

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.

Upvotes: 3

Yuji
Yuji

Reputation: 34185

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.

Upvotes: 3

Related Questions