views:

87

answers:

1

I have seen and done initialization of arrays and all put "nil" at the end of initialization but never question, why it is required to put there?

Plus if you are initializing your array in a loop, is it still necessary to put nil at the end of array? for example.

array = [[NSMutableArray alloc] init];

for (int i = 0 ; i < 10; i++)
{
   [array addObject:@"1"];
}

// now this line is required or not after i exit the loop?
[array addObject:nil];
+6  A: 

This concept is called nil-termination, and it's purpose is to provide a sentinel to the receiving function or method of where the variable argument list ends.

Jacob Relkin
But should I put it in the given example? I have just experiment with that and it seems to crash my app.
itsaboutcode
@itsaboutcode, No, this is only necessary with the variadic convenience methods.
Jacob Relkin
@Jacob - Thanks.
itsaboutcode
In fact, [array addObject:nil] will crash since you can't put nils in NSArrays.
Daniel Dickison