开发者

Using sortUsingSelector on an NSMutableArray

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

Now I'm trying to sort an NSMutableArray containing NSMutableArrays of c开发者_如何学Custom objects.

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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜