排序
- NSComparator
NSOrderedAscending 表示 obj1 应该排在 obj2 前面
NSOrderedDescending 表示 obj2 应该排在 obj1 前面
NSOrderedSame 表示 obj1 和 obj2 是一样的
[testArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
if ([obj1 intValue] < [obj2 intValue]) {
return NSOrderedAscending;
}else if ([obj1 intValue] > [obj2 intValue]){
return NSOrderedDescending;
}else{
return NSOrderedSame;
}
}];
[testArray sortedArrayWithOptions:<#(NSSortOptions)#> usingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
}]
NSSortConcurrent 是高效的但不稳定的排序算法,例如:快速排序
NSSortStable 是稳定的排序算法,例如:冒泡排序 插入排序
如果使用 NSSortStable 正确的结果是 @"one", @"two", @"four", @"three"
如果使用 NSSortConcurrent 正确的结果是 @"one", @"two", @"four", @"three" 或者 @"two", @"one", @"four", @"three"
- selector
[[NSArray new] sortedArrayUsingSelector:<#(nonnull SEL)#>]
- function
[[NSArray new] sortedArrayUsingFunction:<#(nonnull NSInteger (*)(id _Nonnull __strong, id _Nonnull __strong, void * _Nullable))#> context:<#(nullable void *)#>];
- NSSortDescriptor
NSArray *firstNames = @[ @"Alice", @"Bob", @"Charlie", @"Quentin" ];
NSArray *lastNames = @[ @"Smith", @"Jones", @"Smith", @"Alberts" ];
NSArray *ages = @[ @24, @27, @33, @31 ];
NSMutableArray *people = [NSMutableArray array];
[firstNames enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Person *person = [[Person alloc] init];
person.firstName = [firstNames objectAtIndex:idx];
person.lastName = [lastNames objectAtIndex:idx];
person.age = [ages objectAtIndex:idx];
[people addObject:person];
}];
NSSortDescriptor *firstNameSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"firstName"
ascending:YES
selector:@selector(localizedStandardCompare:)];
NSSortDescriptor *lastNameSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"lastName"
ascending:YES
selector:@selector(localizedStandardCompare:)];
NSSortDescriptor *ageSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"age"
ascending:NO];
NSLog(@"By age: %@", [people sortedArrayUsingDescriptors:@[ageSortDescriptor]]);
// "Charlie Smith", "Quentin Alberts", "Bob Jones", "Alice Smith"
NSLog(@"By first name: %@", [people sortedArrayUsingDescriptors:@[firstNameSortDescriptor]]);
// "Alice Smith", "Bob Jones", "Charlie Smith", "Quentin Alberts"
NSLog(@"By last name, first name: %@", [people sortedArrayUsingDescriptors:@[lastNameSortDescriptor, firstNameSortDescriptor]]);
// "Quentin Alberts", "Bob Jones", "Alice Smith", "Charlie Smith"
过滤
详情:http://nshipster.cn/nspredicate/
-
NSPredicate
-
NSCompoundPredicate
NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:<#(nonnull NSArray<NSPredicate *> *)#>];
[NSCompoundPredicate andPredicateWithSubpredicates:<#(nonnull NSArray<NSPredicate *> *)#>]
- NSComparisonPredicate
通过NSExpression生成predicate - NSExpression
如果我们仔细观察NSPredicate,我们会发现它NSPredicate实际上由更小的原子部分组成:两个NSExpressionS(左手值右手值),与操作者(例如相比<,IN,LIKE等等)。
详情:http://nshipster.com/nsexpression/
网友评论