1

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?

2
  • 1
    ;; instead of ; is not a C (or Objective-C) syntax error. Commented Jul 6, 2011 at 9:53
  • To add to what Bavarious is saying above, an additional semicolon without an instruction is known as an empty statement. This is allowed so that certain loop/branching constructs can have an empty code block because all the work is in the loop/branching construct itself. Eg. "for (i=1 ; i<=5 ; i++, j+=i);" is a valid for-loop. All this loop really wants to do is add the numbers 1,2,3,4,5 to j so no need for a code-block after the for. Commented Jul 11, 2011 at 12:45

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It wasn't that obvious but now when I checked the documentation it made perfectly sense.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.