【问题标题】:Getting objectForKey: in an NSDictionary with JSON data returning nil even though the key is present获取objectForKey:在带有JSON数据的NSDictionary中返回nil,即使键存在
【发布时间】:2012-02-23 23:57:11
【问题描述】:

我正在制作一个 iPhone 应用程序,在其中我从 http://maps.googleapis.com/maps/api/geocode/json?address=canada&sensor=true 检索 JSON 数据,然后将其存储在 NSDictionary 对象中。我的代码编译良好,JSON 数据有效。但是,当我查找某些键时,即使该键存在并且我没有打错字,它也会返回 nil。这是唯一有效的键(feed 是一个 NSDictionary 对象):

NSString *status = [[NSString alloc] initWithFormat:[feed objectForKey:@"status"]];

但是当我做这样的事情时:

NSString *longName = [[NSString alloc] initWithFormat:[feed objectForKey:@"long_name"]];

我收到此错误:

WebKit 在 webView 中丢弃了一个未捕获的异常:shouldInsertText:replacingDOMRange:givenAction: delegate: * -[NSPlaceholderString initWithFormat:locale:arguments:]: nil argument

我有两个问题:我该如何解决这个问题?此外,如果存在多个同名地点(即“Springfield”),由于此 Google 地理编码器可以返回多个地点,我该如何选择要引用的键? (比如哪个“long_name”,哪个“lat”等等……)

提前致谢!

【问题讨论】:

    标签: objective-c json nsdictionary google-geocoder


    【解决方案1】:

    “状态”起作用的原因是因为它位于字典的根目录,而长名称和大多数其他部分位于子数组中的子字典中。尝试这样的事情:

    NSArray *results = [feed objectForKey:@"results"];
    NSDictionary *firstResult = [results objectAtIndex:0];
    NSArray *addressComponents = [firstResult objectForKey:@"address_components"];
    NSDictionary *firstAddress = [addressComponents objectAtIndex:0];
    NSString *longName = [firstAddress objectForKey:@"long_name"];
    

    如果你想获取所有的值,你当然需要设置循环 - 我给出的示例显示了如何从返回的第一个结果中的第一个地址获取长名称。

    【讨论】:

    • 效果很好,但我唯一需要更改的是将results 更改为NSArray 对象,因为显然NSDictionary 没有响应objectAtIndex:。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多