【问题标题】:iOS Flickr how to get IDiOS Flickr 如何获取 ID
【发布时间】:2013-10-30 13:55:02
【问题描述】:

在以下示例中,我想从 Flickr JSON 访问 ID 值(见下文):

{
page = 1;
pages = 336567;
perpage = 20;
photo =     (
            {
        farm = 6;
        id = 10573655046;
        isfamily = 0;
        isfriend = 0;
        ispublic = 1;
        owner = "32491986@N08";
        secret = 91349d9115;
        server = 5533;
        title = DSC09356;
    },
            {
        farm = 8;
        id = 10573936633;
        isfamily = 0;
        isfriend = 0;
        ispublic = 1;
        owner = "32491986@N08";
        secret = 6abdcaa69e;
        server = 7295;
        title = DSC09118;
    }

);

所以我尝试尝试使用以下模式

 NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

if(json == nil){
    NSLog(@"NULL");
}else 
    NSLog(@" WORKED");

 NSArray* flickrPics = [json objectForKey:@"photos"];
 NSLog(@"Details: %@", flickrPics); //works
 NSDictionary* lastUpload = [flickrPics objectAtIndex:0];
 //fails on that line but the idea would have been to then
  NSNumber* id = lastUpload[@"photo"][@"id"];

这是错误

2013-10-30 13:43:50.534 JSON1[1508:1303] -[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x8ab3820

那么为什么会出现这个错误(我在不同的 JSON 对象上使用了这个模式) 那么如何访问 id 呢?

【问题讨论】:

    标签: ios nsdictionary nsjsonserialization


    【解决方案1】:

    那是因为这一行:

     NSArray* flickrPics = [json objectForKey:@"photos"];
    

    返回的是 NSDictionary,而不是数组

    【讨论】:

    • 在我关注的示例中 (raywenderlich.com/5492) NSArray* latestLoans = [json objectForKey:@"loans"];
    • 只需检查控制台中的 flickrPics 并检查它的键
    • 是的,它似乎是一个 NSDictionary,所以我关注的文章一定是不正确的。那么如何迭代和访问该文档中的所有 Id 呢?以及如何遍历文档中的所有条目?
    • 要做到这一点,请点击此链接:stackoverflow.com/questions/17960068/…,如果有效,请接受答案
    【解决方案2】:

    所以我已经解决了这个问题,需要认识到的问题是,在 JSON 中,照片是一个包含字典数组的键。那么如何访问该数组中的特定项目呢?

    //In this case valueForKey @"photo" will return as an array
    NSArray *results = [flickr valueForKey:@"photo"];
    //next we can iterate through the array. Each element of the Array is a dictionary
      for(NSDictionary *UserPhotoData in results){
    //now we can retrieve the ID (or whatever piece of data you require 
        NSNumber *getId = [UserPhotoData valueForKey:@"id"];
        NSLog(@" id %@", getId);
    }
    

    这行得通。

    但我不确定

    1) 开发人员如何知道 valueForKey 返回的内容。有时是 NSArray,有时是字符串或数字。

    【讨论】:

      猜你喜欢
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 2012-08-01
      相关资源
      最近更新 更多