2012-12-18 66 views
0

我想排序内部有NSInteger值的NSMutableArray。我试图用这个解决方案:使用NSInterger值对NSMuatbleArray进行排序

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

它几乎工作,所以我想问问为什么不一切都好吧。下面是数据。例如:

not sorted = (
    30, 
    42, 
    54, 
    6, 
    18 
) 

sorted = (
    18, 
    30, 
    42, 
    54, 
    6 
) 

我们可以看到,它排序的一切,但6值,它是在年底关闭阵列。

为什么会发生这种情况?

谢谢。

全部方法:

- (void) initialize{ 
    NSInteger min = 30; 
    NSInteger interval = 12; 
    NSInteger count = floor(60/interval); 

    for (int i = 0; i < count; i++) { 

     [array addObject:[NSString stringWithFormat:@"%i",min]]; 
     min +=interval; 

     if (min > 60) 
      min -= 60; 
    } 

    //DLog(@"not sorted = %@",minutes); 
    array = [[array sortedArrayUsingSelector:@selector(compare:)] mutableCopy]; 
    //DLog(@"sorted = %@",minutes); 

} 
+0

你用数组做什么?我可以在我的Mac中获得正确的结果。 2012年12月18日16:16:12.936无题[10001:707]( 30, 42, 54, 6,) 2012年12月18日16:16:12.938无题[10001: 707]( 6, 18, 30, 42,) – onevcat

+1

这里有一个外表http://stackoverflow.com/questions/2752992/how-to-let-the-sortedarrayusingselector-using-integer-对字符串进行排序 – CRDave

+0

您是如何封装NSIntegers的?它们是否包含在NSStrings,NSValues或NSNumbers中? – mit3z

回答

1

您在上述情况下获得的问题,因为要排序的字符串值不是一个NSNumber的。 你必须使用NSNumber来添加整数的对象。然后做类似:

 NSMutableArray *array = [[NSMutableArray alloc ] initWithObjects: 
           [NSNumber numberWithInt:10],  
           [NSNumber numberWithInt:50], 
           [NSNumber numberWithInt:5], 
           [NSNumber numberWithInt:3], 
           nil]; 

     NSLog(@"SORTED = %@",[array sortedArrayUsingSelector:@selector(compare: 
                   )]); 

这会给你一个排序的数组。