Objective-c 按最后一个对象对数组进行排序
我对数组排序有问题。我已经构建了排序方法,但它无法正常工作。我的意思是最终表应该按最后一个元素排序,使用最后一个元素降序排列。
我的方法:
static NSInteger order (id a, id b, void* context)
{
NSNumber* catA = [a lastObject];
NSNumber* catB = [b lastObject];
return [ catB compare: catA];
}
并通过以下方式调用它:
[ array sortUsingFunction:order context:NULL];
我的数组是这样的:
{1,9}
{1,6}
{1,5}
{2,2}
{0,18}
{12, 10}
{9,1}
问题出在哪里?
I have problem with sort array of arrays. I already build method to sort but it not work properly. I mean that final table should be sorted by last element, descending using the last element.
My method:
static NSInteger order (id a, id b, void* context)
{
NSNumber* catA = [a lastObject];
NSNumber* catB = [b lastObject];
return [ catB compare: catA];
}
And call it by:
[ array sortUsingFunction:order context:NULL];
And my array is sort that:
{1,9}
{1,6}
{1,5}
{2,2}
{0,18}
{12, 10}
{9,1}
Where is problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
排序后,您并没有确切地说出数组有什么问题。我看到两个可能的问题。
正如 Eimantas 在他的评论中所说,您正在按相反的顺序(从最高到最低)对数组进行排序。如果您想从最低到最高排序,则需要说
return [catAcompare:catB]
。看起来
catA
和catB
的元素是字符串,而不是数字,因此您将它们作为字符串进行排序。字符串“10”小于字符串“9”,但数字 10 大于数字 9。即使您将元素转换为NSNumber
,这也不会更改该元素的类型底层对象,仍然是NSString
。您可以通过这种方式对它们进行数字排序:
但在对数组进行排序之前,最好将字符串转换为数字对象:
You don't say exactly what is wrong with the array after you sort it. I see two possible problems.
As Eimantas says in his comment, you are sorting the array in reverse order (highest to lowest). If you want to sort lowest to highest, you need to say
return [catA compare:catB]
.It looks like the elements of
catA
andcatB
are strings, not numbers, so you are sorting them as strings. The string '10' is less than the string '9', but the number 10 is greater than the number 9. Even though you are casting the elements toNSNumber
, that does not change the type of the underlying object, which is stillNSString
.You can sort them as numbers this way:
But it might be better to convert the strings to number objects before sorting the array: