【问题标题】:how to check NSDictionary key value is null?如何检查 NSDictionary 键值是否为空?
【发布时间】:2014-11-20 07:03:34
【问题描述】:

我如何检查NSDictionary 键值是否为空?

我正在使用ASIHttpRequest

NSDictionary *tempDict=[[[request responseString] JSONValue] valueForKey:@"data"];

如果键值是“0键/值对”并且折痕请给我一个答案。

谢谢。

【问题讨论】:

  • 你之前检查过钥匙吗
  • NSLog([dictionary allKeys]);使用它来获取所有密钥并检查你给定的密钥是否正确

标签: ios iphone xml json asihttprequest


【解决方案1】:

您应该在访问之前检查 NSDictionary 键值。如果条件包含任何非空值,则使用相同的键放置一个条件,否则请采取预防措施。

if([[[request responseString] JSONValue] valueForKey:@"data"]])
   {
     NSDictionary *tempDict=[[[request responseString] JSONValue]valueForKey:@"data"];
   }
else
{
   // Show alert here 

}

【讨论】:

    【解决方案2】:

    您可以像这样检查密钥是否存在于 NSDictionary 中:

    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"Ron",@"first_name",@"25",@"age", nil];
    
    if([self dictionary:dict containsKey:@"age"])
    {
        // Key exists
    }
    else
    {
        // Key does not exists
    }
    

    使用这个辅助函数:

    -(BOOL)dictionary:(NSDictionary *)dictionary containsKey:(id)key
    {
        if(dictionary != nil)
        {
            if([dictionary objectForKey:key])
            {
                return YES;
            }
        }
    
        return NO;
    }
    

    【讨论】:

      【解决方案3】:

      您是否只想检查 NSDictionary 是否为空?然后你可以像这样简单地检查。

      if (tempDict==nil)
           {
          Nslog(@"Dictonary is null");
          }
          else
          {
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-18
        • 2015-08-23
        • 2013-08-21
        • 1970-01-01
        • 2020-06-10
        • 2015-02-08
        • 1970-01-01
        相关资源
        最近更新 更多