开发者

How can I customize the sort order for an NSArray of strings?

I have a series of strings representing the following file names: hello1(eng).txt, hello1(por).txt, hello1.txt. When I s开发者_JS百科ort them using

NSArray *array = [filePaths sortedArrayUsingSelector: @selector(compare:)];

The order returned is hello1(eng).txt, hello1(por).txt, hello1.txt. I would instead like to have this order, where the items in parentheses are returned last: hello1.txt, hello1(eng).txt, hello1(por).txt.

How can I customize the sorting behavior to provide this ordering?


sortedArrayUsingSelector: tells the array to ask the individual objects it's trying to sort for the appropriate sort order. To provide your own, use one of the other sortedArrayUsing… functions. The easiest for your task is probably sortedArrayUsingFunction:context: which allows you to specify a plain old C function which does the comparison.

Another approach would be to use a category to add a sorting function to the NSString class, something along the lines of compareInMyFavor: and pass that as the selector for sortedArrayUsingSelector:.

Now that I think of it, the latter is probably the cleaner solution. Your call.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜