-1

我收到以下错误

    [__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x75a8e20
    2013-04-20 08:56:14.90 MyApp[407:c07] *** Terminating app due to uncaught 
    exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: 
    unrecognized selector sent to instance 0x75a8e20'

这是我第一次使用 JSON。当我尝试运行 URL 是 flickr url 的第一段代码时,出现上述错误。当我使用照片作为键时,它会打印数组并且应用程序突然退出。

#define flickrPhotoURL [NSURL URLWithString: @"http://api.flickr.com/services/rest/?format=json&sort=random&method=flickr.photos.search&tags=rocket&tag_mode=all&api_key=12345&nojsoncallback=1"]

- (void)viewDidLoad
{
   [super viewDidLoad];
   //this line of code will be executed in the background to download the contents of the flickr URL
   dispatch_async(flickrBgQueue, ^{
   NSData* flickrData = [NSData dataWithContentsOfURL:flickrPhotoURL]; //NOTE: synchronous method...But we actually need to implement asynchronous method
   [self performSelectorOnMainThread:@selector(appFetchedData:) withObject:flickrData waitUntilDone:YES]; //when data is available "appFetchedData" method will be called
});

}

- (void)appFetchedData: (NSData *)responseData 
{
 //parsing JSON data
 NSError *error_parsing;
 NSDictionary *flickr_json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error_parsing];
 NSArray* photo_information = [flickr_json objectForKey:@"photos"];

 NSLog(@"Photo Information: %@",photo_information);

 NSDictionary* photo = (NSDictionary*)[photo_information objectAtIndex:0];

 humanReadable.text = [NSString stringWithFormat:@"Owner is %@",[photo objectForKey:@"Owner"]];
}

但是,当我通过将键“照片”替换为“贷款”并使用以下 URL 和代码来运行相同的代码时

#define flickrPhotoURL [NSURL URLWithString: @"http://api.kivaws.org/v1/loans/search.json?status=fundraising"]


- (void)appFetchedData: (NSData *)responseData 
{
 //parsing JSON data
 NSError *error_parsing;
 NSDictionary *flickr_json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error_parsing];
 NSArray* photo_information = [flickr_json objectForKey:@"loans"];

 NSLog(@"Photo Information: %@",photo_information);

 NSDictionary* photo = (NSDictionary*)[photo_information objectAtIndex:0];

 humanReadable.text = [NSString stringWithFormat:@"loan amount is %@",[photo objectForKey:@"loan_amount"]];

}

,应用程序在 humanredable.text 属性上设置正确的信息。我是否为第一个 JSON 使用了错误的密钥?

4

1 回答 1

2

首先,感谢您按原样发布您的 Flickr API 密钥!有朝一日进行身份盗用对我来说非常有用。

其次,非常感谢您没有读取您返回的数据。它是这样开始的:

{"photos":{"page":1, "pages":1792, "perpage":100,
 ^^^^^^^^^^

所以键的对象photos是字典,而不是数组,因此,

NSArray* photo_information = [flickr_json objectForKey:@"photos"];

是错的。你是不是这个意思:

NSArray* photo_information = [[flickr_json objectForKey:@"photos"]
                               objectForKey:@"photo"];

? 此外,在您构建人类可读的描述时,

[photo objectForKey:@"Owner"]

错了,应该是

[photo objectForKey:@"owner"]

反而。

于 2013-04-20T14:33:58.633 回答