Null objects and NSArrays


- (void)displayWithParentView:(UIView *)parentView
                    withItems:(NSArray *)items
                 withOldItems:(NSArray *)oldItems  {
    
    NSString *pictR1C1Name = items[0];
    NSString *pictR1C2Name = items[1];
    NSString *pictR2C1Name = items[2];
    NSString *pictR2C2Name = items[3];
    
    UIButton *oldR1C1Button = (oldItems[0]  == (id)[NSNull null]) ? nil : oldItems[0];
    UIButton *oldR1C2Button = (oldItems[1]  == (id)[NSNull null]) ? nil : oldItems[1];
    UIButton *oldR2C1Button = (oldItems[2]  == (id)[NSNull null]) ? nil : oldItems[2];
    UIButton *oldR2C2Button = (oldItems[3]  == (id)[NSNull null]) ? nil : oldItems[3];

This is a snippet of the code I use to put pictures on the screen. The old pictures slide off the screen and the new ones slide on. When the screen is first initialized the oldItems array has not yet been initialized. So it is null. I can’t put a null object into a button though, so I test to see if there is an null object in the array and then set the button to nil. Otherwise, I set the button to the button that has been passed in from the array.

Likewise, I can’t put null objects into an array—recall that the way to define an array is


NSArray *newArray = [NSArray arrayWithObjects:object1, object2, nil];

The first nil object terminates the array. So to add nil objects to the array you need to first convert the nil to an object.

So you basically do the reverse of the code above to convert nil to an null object.


object1 = (object1  == nil) ? [NSNull null] : object1;
NSArray *newArray = [NSArray arrayWithObjects:object1, object2, nil];

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.