开发者

Objective-C sorting a NSMutableArray and returning the NSMutableArray (sorted)

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开发者_如何学JAVA 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?


-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:

  1. Creates a new, sorted array based on ids and keeps ids intact;
  2. Discards the method return value (i.e., the new, sorted array) since you’re not using it;
  3. Returns the original ids array.

Whereas:

return [ids sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

does the following:

  1. Creates a new, sorted array based on ids and keeps ids intact;
  2. Uses the method return value (i.e., the new, sorted array) as the return value.

If you don’t want a new array, use -sortUsingSelector: instead:


This is because the array sorted is not the array which receive the message but the return one. Take a look at sortedArrayUsingSelector:

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜