MikeW
MikeW

Reputation: 31

Objective-C Array Literal - Avoiding adding a nil object

With the new Objective-C array literal ...

for (UIView *view_ in @[self.myView01, self.myView1, self.myView2]) { ... }

Occasionally one of the myView* objects is nil, which causes the error ...

-[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]

Question

Is there a nice shortcut way of checking the 3 objects before adding them to the array?

Upvotes: 3

Views: 3014

Answers (2)

GoZoner
GoZoner

Reputation: 70175

If your goal is to check them before creating the array simply

  NSAssert (self.myView0 && self.myView1 && self.myView2);

works. If you want to create the array even if one value is nil use:

   (self.myView0 ? self.myView0 : [NSNull null])

Upvotes: 1

Michael Reneer
Michael Reneer

Reputation: 2581

To be clear, when you are using literals then you are not adding objects to an array, you are initializing an array. You could do:

NSArray *array = @[
    (self.myView01 ? self.myView01 : [NSNull null]),
    (self.myView1 ? self.myView1 : [NSNull null]),
    (self.myView2 ? self.myView2 : [NSNull null]),
];

for (UIView *view_ in array) {
    if (view_ != [NSNull null]) {
        // DO SOMETHING
    }
}

But then in your loop you'd have to compare each object you are iterating over to [NSNull null]. Alternatively, you could not use a literal and build a NSMutableArray.

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:3];

if (self.myView01) {
    [array addObject:self.myView01];
}

if (self.myView1) {
    [array addObject:self.myView1];
}

if (self.myView2) {
    [array addObject:self.myView2];
}   

for (UIView *view_ in array) {
    // DO SOMETHING
}

It really depends on what you think is more readable.

Upvotes: 4

Related Questions