Objective-c按最后一个对象排序数组
我对数组的排序有问题。我已经建立了排序方法,但它不能正常工作。我的意思是,最终的表应该按最后一个元素排序,使用最后一个元素降序 我的方法:Objective-c按最后一个对象排序数组,objective-c,sorting,nsmutablearray,Objective C,Sorting,Nsmutablearray,我对数组的排序有问题。我已经建立了排序方法,但它不能正常工作。我的意思是,最终的表应该按最后一个元素排序,使用最后一个元素降序 我的方法: static NSInteger order (id a, id b, void* context) { NSNumber* catA = [a lastObject]; NSNumber* catB = [b lastObject]; return [ catB compare: catA]
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}
问题出在哪里?在对数组进行排序后,您并没有确切地说出它到底出了什么问题。我看到两个可能的问题
return[catA compare:catB]
catA
和catB
的元素是字符串,而不是数字,因此您将它们作为字符串进行排序。字符串“10”小于字符串“9”,但数字10大于数字9。即使您将元素强制转换为NSNumber
,这也不会改变底层对象的类型,它仍然是NSString
[array sortUsingComparator:^(id a, id b) {
return [[a lastObject] intValue] - [[b lastObject] intValue];
}]
但在对数组排序之前,最好将字符串转换为数字对象:
for (NSMutableArray *element in array) {
[element replaceObjectAtIndex:(element.count - 1)
withObject:[NSNumber numberWithInt:[element.lastObject intValue]]];
}
[array sortUsingComparator:^(id a, id b) {
return [[a lastObject] intValue] - [[b lastObject] intValue];
}]
你需要告诉我们更多关于
array
的内容。你做反向排序是因为你比较catA和catB,而不是catB(尝试return[catA compare:catB]
。你说的“不能正常工作”是什么意思?你想得到什么结果?你可能是指return[[a lastObject]intValue][[a lastObject]intValue];
。在您提到的第二种情况下,他的数组包含字符串数组。它是数组数组数组(类似于矩阵NxM),我想按最后一个对象从最大到最小(颠倒顺序)对数组进行排序。好的,我检查了这一点,实际上它是NSMutableString,我将其更改为NSNumber.thx