Xcoder Xcoder - 7 months ago 70
iOS Question

Behaviour of sortedArrayUsingComparator

I'm in the process of understanding objective C blocks. Most of the time I have been dealing with async blocks for web calls. But Here I have a method for returning sorted array of custom objects (in the alphabetical order of a property).

Here Im bit confused how this block works? Is it an async call (in which case it should yield the input array itself). Can someone explain?

NSArray *sortedArray;
sortedArray = [_unsortedList sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first = [(customObject*)a userName];
NSString *second = [(customObject*)b userName];
return [first compare:second];
return sortedArray;


It's a synchronize call during the block, you can treat the block as a function that compares two objects. With this compare function, system can sort the array. Explain by code:

function : ^NSComparisonResult(id a, id b) - provided by you in the block code.

NSArray sortedArrayUsingComparator do:

  1. Get two objects from the array.
  2. Compare this two objects by the compare function in the block. (get result of NSOrderedAscending, NSOrderedSame,NSOrderedDescending )
  3. Put the object to new array according the the compare result.
  4. Continue one if there are still object left in origin array.
  5. return the new array after all objects sorted.

(The operation for 1,4 may be different based on the sort algorithm but the basic ideas is the same.)