ios - Objective-C Array Literal - Avoiding adding a nil object -


with new objective-c array literal ...

for (uiview *view_ in @[self.myview01, self.myview1, self.myview2]) { ... }

occasionally 1 of myview* objects nil, causes error ...

-[__nsplaceholderarray initwithobjects:count:]: attempt insert nil object objects[0]

question

is there nice shortcut way of checking 3 objects before adding them array?

to clear, when using literals not adding objects array, initializing array. do:

nsarray *array = @[     (self.myview01 ? self.myview01 : [nsnull null]),     (self.myview1 ? self.myview1 : [nsnull null]),     (self.myview2 ? self.myview2 : [nsnull null]), ];  (uiview *view_ in array) {     if (view_ != [nsnull null]) {         //     } } 

but in loop you'd have compare each object iterating on [nsnull null]. alternatively, not use literal , build 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]; }     (uiview *view_ in array) {     // } 

it depends on think more readable.


Comments