我有一个NSArray输出。请参考下文。我想根据其中的特定数字字段(Order)进行排序。请参考以下代码。
Log: resultArray:
(
{
Name = "Myname1";
Id = "dummyID";
Order = 0;
parexId = 15;
"__type" = "Question:#myAPI";
},
{
Name = "Myname2";
Id = "fatID";
Order = 1;
parexId = 16;
"__type" = "Question:#myAPI";
}
{
Name = "Myname3";
Id = "colorID";
Order = 2;
parexId = 17;
"__type" = "Question:#myAPI";
}
)
代码:
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"Order" ascending:YES comparator:^(id obj1, id obj2) {
return [obj1 compare:obj2 options:NSNumericSearch];
}];
resultArray = [resultArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]; // resultArray contents the above output values.
但是在排序过程中比较时会崩溃。 崩溃错误:
-[__NSCFNumber compare:options:]: unrecognized selector sent to instance 0x6b514b0
有人可以帮助我,我在这里做错了吗?
谢谢!
答案 0 :(得分:2)
订单是一个数字字段。它没有方法比较:选项。你应该使用
[obj1 compare:obj2];
答案 1 :(得分:0)
使用如下,它将正常工作
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Order" ascending:YES];
[resultArray sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];
[aSortDescriptor release];