3

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?

1
  • Would setting your views to NSNull an option for you? Commented May 6, 2013 at 1:00

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.