【问题标题】:-[__NSArrayM insertObject:atIndex:]: object cannot be nil-[__NSArrayM insertObject:atIndex:]: 对象不能为 nil
【发布时间】:2013-09-18 06:01:00
【问题描述】:

我得到错误对象不能为零。我正在使用 Web 服务,当我使用循环解析它时它崩溃并发送输出 -[__NSArrayM insertObject:atIndex:]: 对象不能为 nil 作为错误,因为我正在尝试解析的 NSMutableArray 中的空白值有空值。

我尝试用这些方法修复:

(1) if([Array containsObject:[NSNull null]])  
(2) if([Array objectAtIndex:0  
(3) if([Array objectAtIndex:counter] == 0**

我的代码是,

if([[[node childAtIndex:counter] name] isEqualToString:@"Phone"]){

    if([phoneno containsObject:[NSNull null]]){
        phone.text = @"-";
    }
    else{
        NSString *str = [[node childAtIndex:counter] stringValue];
        [phoneno addObject:str];
        NSString *myString = [phoneno componentsJoinedByString:@","];
        [phone setText:myString];
        phone.text = [NSString stringWithFormat:@"%@",myString];
    }
}

这里,phoneno 是 NSMutableArray

【问题讨论】:

  • “我做错了什么?”将nil 插入到数组中。使用if (value) { [array insertObject:value atIndex:index]; } 进行防范。

标签: iphone ios objective-c xcode


【解决方案1】:

确保在添加任何对象之前已初始化名为 phoneno 的数组...

NSMutableArray *phoneno=[[NSMutableArray alloc]init];

并停止向其中添加任何 nil 对象...

if(str) //or if(str != nil) or if(str.length>0)
  {
    //add the str into phoneno array.
  }
else
  {
     //add the @""
  }

【讨论】:

【解决方案2】:

您不能将nil 插入NSArrayNSDictionary,因此您必须添加一个测试。

if(str){
   [phoneno addObject:str];
}

【讨论】:

    【解决方案3】:

    在某些情况下,您在数组中插入 nil,因此当您尝试获取该值时,应用程序会崩溃。因此,请在将其插入数组之前检查该值。例如,如果值为 nil,那么您可以将空白字符串插入到数组中。

    if (str == nil || [str isKindOfClass:[NSNull null]])
    {
        [array addObject:@""];
    }
    else
    {
        [array addObject:str];
    }
    

    【讨论】:

      【解决方案4】:

      你用这个实用方法来验证 nil//Nil/Null/NULL 检查:

      -(BOOL)isObjectEmpty:(id)object
      {
          return object == nil || ([object respondsToSelector:@selector(length)] && [(NSData *)object length] == 0) || ([object respondsToSelector:@selector(count)] && [(NSArray *)object count] == 0);
      }
      

      【讨论】:

        【解决方案5】:
        NSString *str = [[node childAtIndex:counter] stringValue];
        if(str.length>0)
        {
           [phoneno addObject:str];
        }
        

        【讨论】:

        • 阻止我们插入@"" 这是一个有效的对象。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-19
        相关资源
        最近更新 更多