【问题标题】:How to check if string in nsdictionary is null如何检查nsdictionary中的字符串是否为空
【发布时间】:2013-08-21 18:00:21
【问题描述】:

我正在开发一个推特应用程序并尝试实现推文位置。我想要的只是显示国家名称,如果推文有位置,则将其显示在地图上。但是无论我尝试过什么,它总是显示第一条推文的国家,或者如果它为空,应用程序就会崩溃。我不明白我做错了什么。任何人都可以帮忙吗?谢谢! 这是我的代码:

   // LOCATION
   for (NSDictionary *dic in self.dataSource)
    {
        NSString *str = [dic valueForKeyPath:@"place.name"];
        if(str)
        {
            cell.button.hidden = NO;
            cell.location.text = [dic valueForKeyPath:@"place.full_name"];
            self.coordinates = [dic valueForKeyPath:@"geo.coordinates"];
            break;
        } else {
            cell.button.hidden = YES;
            cell.location.hidden = YES;
            break;
        }

    }

这是 NSLog 输出:

  2013-08-20 00:04:42.269 TwitterApplication[10011:c07] <null>
  2013-08-20 00:04:42.269 TwitterApplication[10011:c07] Downtown
  2013-08-20 00:04:42.269 TwitterApplication[10011:c07] <null>
  2013-08-20 00:04:42.270 TwitterApplication[10011:c07] Moscow
  2013-08-20 00:04:42.270 TwitterApplication[10011:c07] Брянск
  2013-08-20 00:04:42.270 TwitterApplication[10011:c07] <null>
  2013-08-20 00:04:42.271 TwitterApplication[10011:c07] Брянск
  2013-08-20 00:04:42.271 TwitterApplication[10011:c07] <null>
  2013-08-20 00:04:42.271 TwitterApplication[10011:c07] <null>
  2013-08-20 00:04:42.272 TwitterApplication[10011:c07] <null>
  2013-08-20 00:04:42.272 TwitterApplication[10011:c07] <null>
  2013-08-20 00:04:42.272 TwitterApplication[10011:c07] <null>
  2013-08-20 00:04:42.273 TwitterApplication[10011:c07] <null>
  2013-08-20 00:04:42.273 TwitterApplication[10011:c07] <null>

【问题讨论】:

  • 生成该日志的代码是什么?
  • 如果推文有位置,则城市名称,如果没有,则为 null。
  • 显示它的代码以及它与您显示的代码的关系。
  • 是这样的: for (NSDictionary *dic in self.dataSource) { NSString *str = [dic valueForKeyPath:@"place.name"]; NSLog(@"%@", str);我只是想确保我得到城市名称。
  • 正如你所说,这个 str 可能为空。尝试使用 if([str isEqualToString:@""])。

标签: iphone ios twitter nsdictionary


【解决方案1】:

为什么要检查@"place.name" 的值,然后使用@"place.full_name"?也许这就是问题所在。

而且我认为您必须在使用之前检查 @"geo.coordinates" 值。

尝试将 if 语句更改为 if(str &amp;&amp; str.lengh)

并更改NSString *str = [dic valueForKeyPath:@"place.name"];NSString *str = [[dic valueForKeyPath:@"place.name"] lastObject]; 因为 valueForKeyPath 返回一个数组。

【讨论】:

  • 很遗憾不是,我认为问题与 if 有关,但我不确定。
  • @Blaze 但检查一个值并使用另一个值有什么意义?
  • 打错了,我改成@"place.name"
  • 错误,没有位置的推文中的 NSNull 长度。我有非常奇怪的输出。似乎它记得 str 的第一个值并且在循环期间没有改变。
  • 我使用 SLRequest 到 twitter api,代码很多。我照你说的做了,但又是错误:'-[NSNull lastObject]: unrecognized selector sent to instance 0x1664678'
猜你喜欢
  • 2013-07-18
  • 2011-11-25
  • 2012-03-23
  • 2022-01-12
  • 2015-06-12
  • 1970-01-01
相关资源
最近更新 更多