Sort array with custom objects

后端 未结 2 603
挽巷
挽巷 2021-01-14 19:56

I\'m trying to sort an array, filled with objects from a class i wrote. The class i wrote contains an NSString itself, as the \"name\". So what i wanna do, is to sort the ar

相关标签:
2条回答
  • 2021-01-14 20:40

    You can use the method sortedArrayUsingComparator:

    NSArray *sortedArray = [anArray sortedArrayUsingComparator:^(MyClass *a, MyClass *b) {
        return [a.name caseInsensitiveCompare:b.name];
    }];
    
    0 讨论(0)
  • 2021-01-14 20:42

    You can sortedArrayUsingComparator:(NSComparator)cmptr (NSArray reference) to sort the array. For instance, if you want to sort by the name property, do the following (assuming your class is called Person):

    NSArray *sortedArray = [anArray sortedArrayUsingComparator:^(id a, id b) {
        NSString *first = [(Person *)a name];
        NSString *second = [(Person *)b name];
        return [first caseInsensitiveCompare:second];
    }];
    
    0 讨论(0)
提交回复
热议问题