使用sortedArrayUsingDescriptors排序时出错:“类不是密钥值编码兼容的密钥”

时间:2011-04-05 19:49:46

标签: objective-c cocoa key-value-observing

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

@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 对其进行排序:

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 *country = [[[NSSortDescriptor alloc] initWithKey:@"country" 
                                                         ascending:YES]autorelease];

NSSortDescriptor *city = [[[NSSortDescriptor alloc] initWithKey:@"city"
                                                      ascending:YES] autorelease];
// this is were everything goes wrong 
NSSortDescriptor *url = [[[NSSortDescriptor alloc] initWithKey:@"imageUrl" 
                                                     ascending:YES] autorelease]; 

NSArray *sorted = [bag sortedArrayUsingDescriptors:[NSArray arrayWithObjects: country, city, nil]];

如果我尝试使用imageUrl属性进行排序,我会得到一个相当奇怪的错误:

  

* 由于未捕获的异常'NSUnknownKeyException'而终止应用,   原因:'[   valueForUndefinedKey:]:这个类是   不符合关键值编码   关键imageUrl。'

该属性与其他两个属性合成,因此我希望3是符合键值的。

发生了什么事?

1 个答案:

答案 0 :(得分:4)

区分大小写的问题。它在类中定义为imageURL,您尝试按imageUrl排序。 :)

作为旁注,请务必遵循Requirements of Collection Objects。我不确定NSURL对排序的效果如何。