天天看點

iOS之NSSortDescriptor及NSArray排序

iOS中有一個類可以按照屬性來排序:

@interface Person : NSObject
@property NSString *firstName;
@property NSString *lastName;
@property NSNumber *age;
@end

@implementation Person

- (NSString *)description {
    return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
}

@end


 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"
    
           

自定義一個person類,person類有三個屬性firstName,lastName,age。然後分别按照age,firstName,lastName firstName來排序,其結果如下:

iOS之NSSortDescriptor及NSArray排序

是不是很友善。。。

補充:

NSArray數組的比較排序

看代碼:

NSArray *arr [email protected][@"4",@"2",@"3",@"1"];
    
    NSArray *arr1=[arr sortedArrayUsingSelector:@selector(compare:)];
    
    NSLog(@"%@",arr1);
           

輸出的結果是:1,2,3,4