Jayant's Blog

Saturday, December 05, 2009

Inadvertently adding nil to NSArray

In Cocoa, when populating a 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 UITextfields 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.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home