Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sortedArrayUsingSelector what is it doing?

I am still new to objective-c and am trying to figure out what this statement is doing exactly.

[names allKeys] sortedArrayUsingSelector:@selector(compare:)];

I know that allKeys is getting all the keys from my dictionary. I know that sortedArrayUsingSelector is sorting my array im creating. Then im calling the compare method, that is where I am lost what is this doing? From the document on apple it says that "Returns an NSComparisonResult value that indicates whether the receiver is greater than, equal to, or less than a given number." I dont understand how it is sorting based of that method.

like image 783
ios85 Avatar asked Feb 11 '12 18:02

ios85


1 Answers

NSArray * sortedKeys = [[names allKeys] sortedArrayUsingSelector:@selector(compare:)];

The above code returns a sorted array of the dictionary keys using the selector you provide. The selector is actually the function that will be called on the object that is being sorted in your array. In this case your array contains strings so in the actual NSArray sorting code the following would be happening,

//...
[key1 compare:key2];
//..

If you passed in a different selector lets say @selector(randomFunction:) then in the sorting code the following would happen

//..
[key1 randomFunction:key2];
//..

Since NSString does not respond to the selector randomFunction you would get an error. If you wanted to create your own type of comparison function you would need to add a category to the class that the array contains (in your case a category to NSString).

A better way to sort an array is to use a block statement.

id mySort = ^(NSString * key1, NSString * key2){
    return [key1 compare:key2];
};


NSArray * sortedKeys = [[names allKeys] sortedArrayUsingComparator:mySort];

The reason it's a better way is sorting any objects is very easy to do.

id mySort = ^(MyObject * obj1, MyObject * obj2){
    return [obj1.title compare:obj2.title];
};


NSArray * sortedMyObjects = [myObjects sortedArrayUsingComparator:mySort];
like image 192
Joel Kravets Avatar answered Oct 26 '22 23:10

Joel Kravets