在NSHomeDirectory中排序

时间:2013-12-09 16:22:53

标签: ios objective-c file-io

我有这个代码来保存我的应用程序中的图像

NSString *fileName = [NSString stringWithFormat:@"2013_%d_a_%d",count,indexToInsert];
        NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Documents/" stringByAppendingString:fileName]];
        NSData *imageData = UIImagePNGRepresentation(imageToAdd);
        [imageData writeToFile:pngPath atomically:YES];

在我的日志中我看到了:

    "2013_10_a_1",
    "2013_1_a_1",
    "2013_2_a_1",
    "2013_3_a_1",
    "2013_4_a_1",
    "2013_5_a_1",
    "2013_6_a_1",
    "2013_7_a_1",
    "2013_8_a_1",
    "2013_9_a_1"

为什么“2013_10_1”位居榜首?它位于0位置,我希望它位于第9位(10个元素)

2 个答案:

答案 0 :(得分:0)

您的字符串包含数字,因此您需要进行数字排序,而不是纯字符串排序。为此,请使用compare:options:上的NSString方法,并选择NSNumericSearch

答案 1 :(得分:0)

这里的问题是下划线字符_ascii code 95)在任意数字字符后排序(ascii代码48到57)。

更改输出文件名以包含前导零,您不需要处理排序问题:

NSString *fileName = [NSString stringWithFormat:@"2013_%03d_a_%d",count,indexToInsert];

将输出:

"2013_001_a_1",
"2013_002_a_1",
"2013_003_a_1",
"2013_004_a_1",
"2013_005_a_1",
"2013_006_a_1",
"2013_007_a_1",
"2013_008_a_1",
"2013_009_a_1",
"2013_010_a_1"