Reputation: 11728
Maybe someone can enlighten me on this subject. I'm sorting a NSMutableArray
declared as ids
. When I'm done sorting I return it using return ids;
but for some reason the returned array is not sorted. See this code:
NSMutableArray *ids = [[[NSMutableArray alloc] init] autorelease];
for (Career *career in careers) {
[ids addObject:[career id]];
}
// Sort the array in an orderly fashion
[ids sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
return ids;
This does not return a sorted array.
But if I return the array with the sorting method applied, it will be returned correctly sorted. Like this:
//Code is the same as above
return [ids sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
Also while I'm at it, I mistakingly used two semi colons (;) when writing the return statement, but I didn't receive any error for doing so?
Upvotes: 1
Views: 830
Reputation:
-sortedArrayUsingSelector:
returns a new, sorted array, and it doesn’t change the original array. This means that:
[ids sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
return ids;
does the following:
ids
and keeps ids
intact;ids
array.Whereas:
return [ids sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
does the following:
ids
and keeps ids
intact;If you don’t want a new array, use -sortUsingSelector:
instead:
Upvotes: 4
Reputation: 5499
This is because the array sorted is not the array which receive the message but the return one. Take a look at sortedArrayUsingSelector:
Upvotes: 0