Inadvertently adding nil
to NSArray
In Cocoa, when populating a
The values populated at runtime would look something like:
When you print out the array you get:
But what happens, if say
When you print the array now:
Ouch! Noticed what happened there? The array was terminated by the first
This is definitely the case in
NSArray
, you use nil
to mark the end of the objects being added. So lets say you were populating an array using values from 2 UITextfield
s and a property, such that:
NSArray *array = [NSArray arrayWithObjects:self.textField1.text, self.textField2.text, self.nsnumberProperty, nil];
The values populated at runtime would look something like:
NSArray *array = [NSArray arrayWithObjects:"foo", "bar", 10, nil];
When you print out the array you get:
{ "foo", "bar", 10 }
.But what happens, if say
self.textField2.text
is nil
? Now the code at runtime would look like:
NSArray *array = [NSArray arrayWithObjects:"foo", nil, 10, nil];
When you print the array now:
{ "foo" }
Ouch! Noticed what happened there? The array was terminated by the first
nil
, so you may have expected 3 values, but you only got 1. So beware of inadvertently adding a nil
and terminating a NSArray
. Use [NSNull null]
if you want to add a null object in an array. Arrays: Ordered Collections.This is definitely the case in
NSDictionary
also, but not sure if this is the case in NSSet
.