OGeek|极客世界-中国程序员成长平台

标题: ios - 对自定义对象数组中的数字进行排序 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 00:05
标题: ios - 对自定义对象数组中的数字进行排序

我试过 this , thisthis链接

我有一个数组(比如 personObjectArray),其中包含 Person 类的对象。

Person 有 2 个变量说, NSString *name, NSString *age.

这里 age 的类型为 nsstring。

现在当我像下面这样排序时,

personObjectArray = [[personObjectArray sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2){

    return [p1.age compare:p2.age];

}] mutableCopy];

是这样的,

1, 11, 123 2、 23, 3...它排序像字母顺序不考虑它作为一个数字。

所以我像这样更改我的代码,

personObjectArray = [[personObjectArray sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2){

    return [[p1.age intValue] compare:[p2.age intValue] ];

}] mutableCopy];

它说,Bad receiver type 'int'

我现在如何排序? 请不要告诉我在 Person 类中更改 age 的数据类型。我无法改变它。任何帮助表示赞赏(:,感谢您的时间。



Best Answer-推荐答案


您在原始(非对象)类型 int 上使用了比较,因此它不起作用。

试试这个

 return [@([p1.age intValue]) compare([p2.age intValue])];

这里,我们使用 NSNumber(这是一个对象类型)来比较 int 值

@() is a NSNumber's literal

希望这会对你有所帮助.. (:

关于ios - 对自定义对象数组中的数字进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42696583/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4