gpt4 book ai didi

objective-c - 使用 sortedArrayUsingDescriptors 和 Key Paths 进行排序

转载 作者:太空狗 更新时间:2023-10-30 03:25:02 24 4
gpt4 key购买 nike

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

@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

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

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

NSSortDescriptor *country = [[[NSSortDescriptor alloc] initWithKey:@"country.city" ascending:YES]autorelease];

我得到一个错误:

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]];

* Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSCFString 0x6ae8> valueForUndefinedKey:]: this class is not key value coding-compliant for the key city.'

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

最佳答案

你可能想用这个:

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]];

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

“country.city”的排序描述符将询问每个地方的国家,然后作为其城市的返回国家(这是一个 NSString)。我们都知道 NSString 不符合关键城市的值(value)编码标准;)

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

关于objective-c - 使用 sortedArrayUsingDescriptors 和 Key Paths 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5557764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com