请帮忙。我有NSArray,里面有自定义对象。例如Person,因此名称为“Mark”的Person应始终位于末尾。是否可以借助'sortUsingFunction'来做到这一点? 我觉得类似的东西,这里是sort函数:
static NSInteger compareFunction(id item1, id item2, void *context)
{
Person *pItem1 = (Person *)item1;
Person *pItem2 = (Person *)item2;
if ([pItem1.name isEqual:@"Mark"])
{
return NSOrderedDescending;
}
}
注意:它应该是sortUsingFunction,没有其他功能。
答案 0 :(得分:0)
是的,你的想法是可行的。这是一个经过测试的例子:
NSArray *names = @[@"John",@"Mark",@"Sandy"];
NSArray *markEndArray = [names sortedArrayUsingComparator:^NSComparisonResult(NSString *_Nonnull obj1, NSString *_Nonnull obj2) {
if ([obj1 isEqualToString:@"Mark"]) {
return NSOrderedDescending;
}
return [obj1 compare:obj2];
}];
NSLog(@"%@",markEndArray);
//Output:
John,
Sandy,
Mark
答案 1 :(得分:0)
NSArray *names = @[
@"John",
@"Noah",
@"Liam",
@"Mason",
@"Jacob",
@"William",
@"Ethan",
@"James",
@"Alexander",
@"Michael",
@"Mark",
@"Benjamin",
@"Elijah",
@"Daniel",
@"Aiden",
@"Logan",
@"Matthew",
@"Lucas",
@"Jackson",
@"David",
@"Oliver",
@"Jayden",
@"Sandy"
];
错误的结果:
Aiden,
Alexander,
Benjamin,
Daniel,
David,
Elijah,
Ethan,
Jackson,
Jacob,
James,
Jayden,
John,
Liam,
Logan,
Lucas,
Matthew,
Oliver,
Sandy,
Mark,
Mason,
Michael,
Noah,
William
你必须像这样扩展它:
NSArray *markEndArray = [names sortedArrayUsingComparator:^NSComparisonResult(NSString *_Nonnull obj1, NSString *_Nonnull obj2) {
if ([obj1 isEqualToString:@"Mark"]) {
return NSOrderedDescending;
} else if ([obj2 isEqualToString:@"Mark"]) {
return NSOrderedAscending;
} else {
return [obj1 compare:obj2];
}
}];
然后它应该完全没问题!