排序一个NSArray [英] Sorting an NSArray

查看:175
本文介绍了排序一个NSArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSArray如下:

I have an NSArray as follows:

NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath:filePath];

在文件路径文件是:

The files at filePath are:

11.thm,12.thm,13.thm,...,Text_21.thm,Text_22.thm,Text_23.thm,...

11.thm, 12.thm, 13.thm,...,Text_21.thm, Text_22.thm, Text_23.thm,...

我想给的NSArray的顺序进行排序:

I would like to sort the NSArray in the order:

13.thm,12.thm,11.thm,...,Text_23.thm,Text_22.thm,Text_21.thm,...

13.thm, 12.thm, 11.thm,..., Text_23.thm, Text_22.thm, Text_21.thm,...

我如何做到这一点?

推荐答案

编写自定义排序函数:

NSInteger customSortingFunctionReversedAndNumericFirst(NSString *string1, NSString *string2, void *context) {
    NSCharacterSet *decimalCharacterSet;
    BOOL firstStringStartsWithNumeric,
        secondStringStartsWithNumeric;


    decimalCharacterSet = [NSCharacterSet decimalDigitCharacterSet];
    firstStringStartsWithNumeric = [decimalCharacterSet characterIsMember:[string1 characterAtIndex:0]];
    secondStringStartsWithNumeric = [decimalCharacterSet characterIsMember:[string2 characterAtIndex:0]];



    if (firstStringStartsWithNumeric != secondStringStartsWithNumeric) {
        return firstStringStartsWithNumeric ? NSOrderedAscending : NSOrderedDescending;
    }

    return [string2 compare:string1 options:NSNumericSearch];
}

和使用这样的:

NSArray *sortedDirectoryContent = [directoryContent sortedArrayUsingFunction:customSortingFunctionReversedAndNumericFirst context:NULL]

我已经做了很多假设,但是这种code ++工程样品阵列和相似的输入值上。结果
主要的假设是,你只对与数值开头的字符串想要这个特定的顺序。如果不是的话,你可以使用这个code,以使其适应你想要的算法。

I have made many assumption, but this code works on your sample array and similar input values.
The main assumption is that you wanted this particular order only for strings that start with a numeric value. If it's not the case, you can use this code to adapt it to the algorithm you want.

这篇关于排序一个NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆