我正在排序这样的数组:
NSArray *temp = [array sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
int first = [[a valueForKey:@"id"] intValue];
int second = [[b valueForKey:@"id"]intValue];
if (first > second) return NSOrderedAscending;
if (first < second) return NSOrderedDescending;
return NSOrderedSame;
}];
return [temp mutableCopy];
可以正常工作,但是现在我想添加检查以查看例如a的key值是否等于某个值,无论“id”值是什么,始终将其保持在数组的顶部。是否可以使用比较器执行此操作?
最佳答案
假设您的特定值为5,然后将代码更改为
NSArray *temp = [array sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
int first = [[a valueForKey:@"id"] intValue];
int second = [[b valueForKey:@"id"] intValue];
int foo = [[a valueForKey:@"foo"] intValue]; // get foo
if (foo == 5) return NSOrderedAscending; // send foo to the top/bottom
if (first > second) return NSOrderedAscending;
if (first < second) return NSOrderedDescending;
return NSOrderedSame;
}];
return [temp mutableCopy];
关于ios - ios sortedArrayUsingComparator但始终在开头保留一些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24040831/