值得一提的是,这种方法本身并没有在多个排序条件操作中提供递归循环。假设您想对这样的数组进行排序,unsortedList = @[@{@"name":"...", @"isFavourite":"..."},...]
将最喜欢的元素放在不喜欢的元素之前,并按名称的字母顺序对每个子组进行排序,以下代码将不起作用:
sortedArray = [unsortedList sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSDictionary *one = (NSDictionary*)obj1;
NSDictionary *two = (NSDictionary*)obj2;
NSString *name1 = [one objectForKey:@"name"];
NSString *name2 = [two objectForKey:@"name"];
NSInteger isFav1 = [[one objectForKey:@"isFavourite"] integerValue];
NSInteger isFav2 = [[two objectForKey:@"isFavourite"] integerValue];
if (isFav1 > isFav2)
return NSOrderedAscending;
else if (isFav1 < isFav2)
return NSOrderedDescending;
else
return [name1 compare:name2];
}];
您必须在块内引入一个或多个for
循环,因此我发现像这样使用复杂的排序操作更有效sortedArrayUsingDescriptors:
:
NSSortDescriptor *descriptor1 = [NSSortDescriptor sortDescriptorWithKey:@"isFavourite" ascending:NO];
NSSortDescriptor *descriptor2 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
sortedArray = [unsortedList sortedArrayUsingDescriptors:@[descriptor1, descriptor2]];