使用sortedArrayUsingDescriptors和Key Paths排序

cfi*_*her 10 sorting cocoa objective-c key-value-observing nssortdescriptor

我有一个无序数组与以下类的实例:

@interface Place : NSObject {

}

@property (nonatomic, copy) NSString *country;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, retain) NSURL   *imageURL;


-(id) initWithCountry: (NSString *) aCountry city: (NSString *) aCity imageUrl: (NSURL *) aUrl;


@end
Run Code Online (Sandbox Code Playgroud)

我正在尝试按国家和城市使用sortedArrayUsingDescriptors对其进行排序.NSSortDescriptor的文档说initWithKey的arg是一个关键路径.

但是,如果我尝试使用NSortDescriptor,例如:

NSSortDescriptor *country = [[[NSSortDescriptor alloc] initWithKey:@"country.city" ascending:YES]autorelease];
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

NSMutableSet *bag = [[[NSMutableSet alloc] init] autorelease];
[bag addObject:[[Place alloc] initWithCountry:@"USA" 
                                         city:@"Springfield" 
                                     imageUrl:[NSURL URLWithString:@"http://www.agbo.biz"]]];
[bag addObject:[[Place alloc] initWithCountry:@"Afghanistan" 
                                         city:@"Tora Bora" 
                                     imageUrl:[NSURL URLWithString:@"http://www.agbo.biz"]]];
[bag addObject:[[Place alloc] initWithCountry:@"USA" 
                                         city:@"Chicago" 
                                     imageUrl:[NSURL URLWithString:@"http://www.agbo.biz"]]];

[bag addObject:[[Place alloc] initWithCountry:@"USA" 
                                         city:@"Chicago" 
                                     imageUrl:[NSURL URLWithString:@"http://www.google.com"]]];


NSSortDescriptor *sort = [[[NSSortDescriptor alloc] initWithKey:@"country.city" ascending:YES]autorelease];
NSArray *sorted = [bag sortedArrayUsingDescriptors:[NSArray arrayWithObjects: sort, nil]];
Run Code Online (Sandbox Code Playgroud)

*由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[<NSCFString 0x6ae8> valueForUndefinedKey:]:此类不是密钥城市的密钥值编码兼容.

我可以使用关键路径吗?我究竟做错了什么?

Reg*_*ent 30

您可能想要使用此:

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]];
Run Code Online (Sandbox Code Playgroud)

传递的数组sortedArrayUsingDescriptors:定义了排序键优先级.排序描述符提供了比较的关键路径(以及所需的顺序:升序/降序).

"country.city"的排序描述符将询问每个地方的国家,然后作为其城市的返回国家(NSString).我们都知道NSString对于关键城市而言不符合价值编码;)

"country.city"如果你的Place实例有一个属性country,你需要一个排序描述符,这个属性本身就有一个属性city.