tags:

views:

44

answers:

2

can any one help me to resolve this error..

[NSMutableArray replaceObjectAtIndex:withObject:]: attempt to replace with nil object at 0'

+1  A: 

Objective-c containers cannot hold nil values. To avoid this error you must check if object you're going to add is nil or not and handle nil case accordingly. For example you can add a NSNull instance to array (NSNull is the class whose purpose to be able to store nil values in containers), don't add anything or perform any other action.

if (newObject)
    [array replaceObjectAtIndex:0 withObject:newObject];
else{
   // handle nil case
   [array replaceObjectAtIndex:0 withObject:[NSNull null]];
}
Vladimir
Uhm, you just defeated the purpose of what you said in this line: `[array replaceObjectAtIndex:0 withObject:nil]` you're adding `nil` there when you just told him to not add nil.
Richard J. Ross III
@Richard, yes sorry. typed too fast and made that mistake. Should have add newObject obviously.
Vladimir
A: 

YOu can check whether the object you are going to replace is nil or not

if (objNewObject!=nil)
    [array replaceObjectAtIndex:0 withObject:objNewObject];

This way you can put the constraint that it will replace only if the object is not nil. If you want to perform another thing i.e. if object is nil then to alloc the object again and then replace it with the index 0 You can do that in the else part. Hope its now clear to you.

hAPPY cODING...

Suriya