我有以下可变数组:
NSMutableArray *persons = [[NSMutableArray alloc]initWithObjects:person1, person2, person3, nil];
其中每个人都是一个对象,其中包含(NSInteger)personAge和(NSString *)personName属性。 现在我想通过personAge对这个数组进行排序。所以我尝试了以下内容:
[persons sortUsingComparator:
^NSComparisonResult(id obj1, id obj2)
{
Person *p1 = (Person*)obj1;
Person *p2 = (Person*)obj2;
return [p1.personAge compare: p2.personAge];
}];
NSLog(@"%ld", [persons componentsJoinedByString:@" "]);
但是我在返回行中收到“错误接收器类型'NSInteger'(又名'long')”错误消息。另外我在NSLog行中有一个警告:“Format指定类型'long'但参数的类型为'NSString *'”。我该如何解决?
答案 0 :(得分:36)
不应该使用这样的东西吗?
[persons sortUsingComparator:
^NSComparisonResult(id obj1, id obj2){
Person *p1 = (Person*)obj1;
Person *p2 = (Person*)obj2;
if (p1.personAge > p2.personAge) {
return (NSComparisonResult)NSOrderedDescending;
}
if (p1.personAge < p2.personAge) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}
];
问题在于您依赖于compare
上不存在的NSInteger
方法:它只是int
的typedef。因此,您希望比较整数值并返回NSComparisonResult
值,以相应地表示对象的排序。
答案 1 :(得分:4)
您正试图在compare:
上呼叫NSInteger
,而int
不是对象;它是整数类型的typedef(long
或componentsJoinedByString:
,具体取决于架构)。
此外,NSString
会返回[persons sortUsingComparator:
^NSComparisonResult(id obj1, id obj2)
{
Person *p1 = (Person*)obj1;
Person *p2 = (Person*)obj2;
if (p1.personAge < p2.personAge)
return NSOrderedAscending;
if (p1.personAge > p2.personAge)
return NSOrderedDescending;
return NSOrderedSame;
}];
NSLog(@"%@", [persons componentsJoinedByString:@" "]);
,而不是整数。
尝试:
{{1}}
答案 2 :(得分:1)
关于“Bad receiver type ...”错误,NSInteger
是原始数据类型(不是Objective-C类),因此您无法在其上调用方法。你想要做的是以下几点:
if (p1.personAge > p2.personAge) {
return (NSComparisonResult)NSOrderedDescending;
}
if (p1.personAge < p2.personAge) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
警告是由于@"%ld"
是long的格式字符串(如警告所示),但-componentsSeparatedByString:
返回NSString
个对象。任何Objective-C对象的正确格式字符串为@"%@"
,因此该行应为NSLog(@"%@", [persons componentsJoinedByString:@" "]);
。
答案 3 :(得分:0)
[YOURMutableArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
答案 4 :(得分:0)
像tigeguero的回答一样,但更整洁:
[people sortUsingComparator:
^NSComparisonResult(Person* p1, Person* p2){
if (p1.personAge > p2.personAge) {
return NSOrderedDescending;
}
else if (p1.personAge < p2.personAge) {
return NSOrderedAscending;
}
else{
return NSOrderedSame;
}
}
];