Sorting with sortedArrayUsingDescriptors and Key Paths

后端 未结 1 896
长发绾君心
长发绾君心 2020-12-11 02:35

I have an unordered array with instances of the following class:

@interface Place : NSObject {

}

@property (nonatomic, copy) NSString *country;
@property (         


        
相关标签:
1条回答
  • 2020-12-11 03:06

    You may want to use this:

    NSSortDescriptor *country = [[[NSSortDescriptor alloc] initWithKey:@"country" ascending:YES]autorelease];
    NSSortDescriptor *city = [[[NSSortDescriptor alloc] initWithKey:@"city" ascending:YES]autorelease];
    NSArray *sorted = [bag sortedArrayUsingDescriptors:[NSArray arrayWithObjects: country, city, nil]];
    

    The array that's passed to sortedArrayUsingDescriptors: defines the sorting key priorities. The sort descriptors provide the keypaths to compare (and the wanted order: ascending/descending).

    A sort descriptor of "country.city" will ask each place for its country and then as the returned country (which is an NSString) for its city. And we all know that NSString is not value coding-compliant for the key city ;)

    You'd need a sort descriptor of "country.city" if your Place instances had a property country, which themselves had a property city.

    0 讨论(0)
提交回复
热议问题