【问题标题】:Error while sorting with sortedArrayUsingDescriptors : "class is not key value coding-compliant for the key"使用 sortedArrayUsingDescriptors 排序时出错:“类与键的键值编码不兼容”
【发布时间】:2011-04-05 19:49:45
【问题描述】:

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

@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:]:这个类是 不符合键值编码的 关键图片网址。'

该属性与其他两个一样是合成的,所以我希望 3 符合键值。

发生了什么事?

【问题讨论】:

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


    【解决方案1】:

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

    附带说明,请确保您关注Requirements of Collection Objects。我不确定 NSURL 在排序方面的效果如何。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 2013-05-23
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      相关资源
      最近更新 更多