views:

146

answers:

3

I have used sortUsingSelector to sort an NSMutableArray of custom objects.

Now I'm trying to sort an NSMutableArray containing NSMutableArrays of custom objects.

Can you use sortUsingSelector on an NSMutableArray, or does it only work for custom classes?

A: 

It sends the selector to the objects, so you'll need to use one of the other sorters. Probably sortUsingFunction:context:.

Steven Fisher
+1  A: 

If you can use blocks, the most straightforward way using sortUsingComparator:. Otherwise, you'll need to use sortUsingFunction:.

In either case, you are going to need to write a custom block or function that takes two arrays as arguments and returns a sort order based on their contents (I'm not sure what logic you are using to determine if array A or array B is "before" or "after" the other).

You'd do something like:

static NSInteger MySorterFunc(id leftArray, id rightArray, void *context) {
    ... return ascending/descending/same based on leftArray vs. rightArray ...
}

Then:

[myArrayOfArrays sortUsingFunction: MySorterFunc context: NULL];
bbum
A: 

Of course you can also use sortUsingSelector:, it really doesn’t matter whats the object in your array as long as it responds to the selector you want to use. But NSMutableArray and NSArray don’t have any comparison methods themselves, so you’d have to extend them using a category to implement your compare method.

So you probably want to use the other sorting methods pointed out in the other answers here. It’s not impossible to use sortUsingSelector: but it is rather inconvenient and most people (including me) would argue that it’s bad style to write a category for that.

Sven