[英]Sorting NSMuatbleArray with NSInterger values
I want to sort NSMutableArray which have NSInteger values inside. 我想对其中包含NSInteger值的NSMutableArray进行排序。 I tried to use this solution: 我尝试使用此解决方案:
NSArray *sorted = [array sortedArrayUsingSelector:@selector(compare:)];
It almost worked, so i want to ask why not everything alright with it. 它几乎起作用了,所以我想问为什么不是一切都很好。 Here is example of data: 这是数据示例:
not sorted = (
30,
42,
54,
6,
18
)
sorted = (
18,
30,
42,
54,
6
)
We can see that it sorted everything but 6 value which is at the end off array. 我们可以看到它对除数组末尾的6值以外的所有内容进行了排序。
Why this could happened ? 为什么会发生这种情况?
Thank you. 谢谢。
Full method: 完整方法:
- (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);
}
You are getting problem in above case because you are sorting string values not a NSNUMBER. 在上述情况下,您遇到了问题,因为您正在对字符串值而不是NSNUMBER进行排序。 You have to use NSNumber to add objects of integer. 您必须使用NSNumber添加整数对象。 Then do something like: 然后执行以下操作:
NSMutableArray *array = [[NSMutableArray alloc ] initWithObjects:
[NSNumber numberWithInt:10],
[NSNumber numberWithInt:50],
[NSNumber numberWithInt:5],
[NSNumber numberWithInt:3],
nil];
NSLog(@"SORTED = %@",[array sortedArrayUsingSelector:@selector(compare:
)]);
This will give you a sorted array. 这将为您提供一个排序的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.