Peter Warbo
Peter Warbo

Reputation: 11728

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

Answers (2)

user557219
user557219

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:

  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:

Upvotes: 4

gsempe
gsempe

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

Related Questions