7

I am getting error object cannot be nil. I am using web service, when I parse it using loop it crashed and send output -[__NSArrayM insertObject:atIndex:]: object cannot be nil as error, because I have null value on blank value in NSMutableArray which I am trying to parse.

I tried to fix with these methods:

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

My code is,

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];
    }
}

Here, phoneno is NSMutableArray

Jack T
  • 315
  • 1
  • 6
  • 18
Gajendra K Chauhan
  • 3,387
  • 7
  • 40
  • 55
  • 2
    "What am I doing wrong?" Inserting `nil` into an array. Guard against it using `if (value) { [array insertObject:value atIndex:index]; }`. – trojanfoe Sep 18 '13 at 06:05

5 Answers5

13

Make sure you have initialized your array called phoneno before adding any object into it...

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

and stop adding any nil object into it...

if(str) //or if(str != nil) or if(str.length>0)
  {
    //add the str into phoneno array.
  }
else
  {
     //add the @""
  }
Jack T
  • 315
  • 1
  • 6
  • 18
Master Stroke
  • 5,108
  • 2
  • 26
  • 57
5

You can not insert nil in to an NSArray or a NSDictionary so you have to add a test.

if(str){
   [phoneno addObject:str];
}
Alex Terente
  • 12,006
  • 5
  • 51
  • 71
2

There is some case in that you are inserting nil in your array, so when you try to get that value it will crash the application. So please check the value before inserting it into the array. For example, if the value is nil then you could insert blank string into the array instead.

if (str == nil || [str isKindOfClass:[NSNull null]])
{
    [array addObject:@""];
}
else
{
    [array addObject:str];
}
shim
  • 9,289
  • 12
  • 69
  • 108
Nirmalsinh Rathod
  • 5,079
  • 4
  • 26
  • 56
0

You this utility method to validate the nil//Nil/Null/NULL checks:

-(BOOL)isObjectEmpty:(id)object
{
    return object == nil || ([object respondsToSelector:@selector(length)] && [(NSData *)object length] == 0) || ([object respondsToSelector:@selector(count)] && [(NSArray *)object count] == 0);
}
thatzprem
  • 4,697
  • 1
  • 33
  • 41
0
NSString *str = [[node childAtIndex:counter] stringValue];
if(str.length>0)
{
   [phoneno addObject:str];
}
tania_S
  • 1,350
  • 14
  • 23