Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 879
MikeW Avatar asked Jun 18 '26 06:06

MikeW


2 Answers

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.

like image 100
Michael Reneer Avatar answered Jun 19 '26 18:06

Michael Reneer


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])
like image 38
GoZoner Avatar answered Jun 19 '26 20:06

GoZoner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!