开发者

Cocoa - array not sorting?

开发者 https://www.devze.com 2022-12-23 11:14 出处:网络
I have this set NSMutableSet *mySet = [NSMutableSet setWithObjects: @\"2\", @\"8\", @\"7\", @\"0\", @\"3\", nil];

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开发者_JAVA百科 help.

EDIT: CORRECTING A TYPO.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消