0

我努力不随便问问题,但这让我浪费了好几个小时,现在我放弃了,希望有人能帮助我。

我根本无法正确订购包含浮点数的 NSArray,我能得到的最接近的就是这个。

使用以下内容填充数组

[combosMasterLength addObject:[NSString stringWithFormat:@"%0.1f", finalL]];

    NSMutableSet* set1 = [NSMutableSet setWithArray:combosMasterLength];//Array Final Length
    NSMutableSet* set2 = [NSMutableSet setWithArray:CombosMasterWidth];//Array Final Width
    [set1 intersectSet:set2]; //this will give me only the objects that are in both sets

    NSArray *combos = [set1 allObjects];//cread my combos array with the unique values
    NSArray* sortedArray = [combos sortedArrayUsingSelector:@selector(compare:)];//my sorting statment not quite working

    NSLog(@"SORTED ARRAY %@",sortedArray);

我从我的输出中得到的是: -

"1.2",
"1.5",
"12.0",
"2.0",
"2.4",
"3.0",
"4.0",
"6.0"

我知道问题出在哪里,我只是不知道如何对其进行排序,我尝试了参考苹果文档,但他们现在已经超出了我的想象,任何人都知道我将如何对它进行排序以便它返回

"1.2",
"1.5",
"2.0",
"2.4",
"3.0",
"4.0",
"6.0"'
"12.0"

提前谢谢H先生

4

1 回答 1

0

由于您似乎想按数值对 NSString 进行排序,因此您需要将这些值转换为数值并与之进行比较。您可以这样做,例如,使用sortedArrayUsingComparator;

NSArray *myArray = [NSArray arrayWithObjects:
 @"1.2", @"1.5", @"12.0", @"2.0",
 @"2.4", @"3.0", @"4.0", @"6.0", nil];

NSArray *sorted = [myArray sortedArrayUsingComparator:
  ^NSComparisonResult(NSString *obj1, NSString *obj2) 
    {
        if ([obj1 doubleValue] > [obj2 doubleValue])
            return NSOrderedDescending;
        else if ([obj1 doubleValue] < [obj2 doubleValue])
            return NSOrderedAscending;
        return NSOrderedSame;         
    }
];

NSLog(@"%@", sorted);

> (
    "1.2",
    "1.5",
    "2.0",
    "2.4",
    "3.0",
    "4.0",
    "6.0",
    "12.0"
  )
于 2013-08-12T15:58:15.190 回答