Search code examples
iosobjective-cnsmutablearraynsarray

NSArray with objects that "might" be nil


I have 3 objects that might be or not initialized in a random order.

so, if objects "objectOne, "objectTwo", "objectThree" are initialized in this order with

myArray  = [NSArray arrayWithObjects:objectOne,objectTwo,objectThree nil];

all objects get inside the array without problem but in my case objectOne, objectTwo might be nil and objectThree might not be nil, and in this case I would like myArray to return(count) 1.

if objectOne is nil but objectTwo and objectThree are not nil I want my array to return(count) 2.

In these 2 last cases my array always return nil. What would be the best approach to this?


Solution

  • There are no magic method can solve the problem for you, you need to build the array from NSMutableArray

    NSMutableArray *array = [NSMutableArray array];
    if (objectOne) [array addObject:objectOne];
    if (objectTwo) [array addObject:objectTwo];
    if (objectThree) [array addObject:objectThree];