NSArray arrayWithObjects: if nil is meant to mark the end of the array, can I do ... nil, nil]?

If nil is meant to indicate the end of parameters, then can I use:

[NSArray arrayWithObjects:obj1, obj2, nil, nil, nil]; 

since the first end of the noil array and the two zeros after are ignored?

I got two opposite answers and will try.

update:

For this reason, I need to create a UIAlertView that can have buttons: OK or Call and Cancel, so either OK or Cancel, the Cancel button, while Call are other buttons in one case, in other cases I don’t need any other buttons, so I need to do this.

+4
source share
4 answers

Adding nil to the end is not intended to add nils to an array, it is just an artifact of how C handles ... variable arguments. It has nothing to do with NSArray or NSMutableArray, you also cannot store null.

So, regardless of whether the compiler accepts, nil, nil, nil does not actually matter. The compiler will stop reading from the first zero. And writing this code primarily shows a misunderstanding of obj C collections and var arg methods.

Why not use the new literal syntax and just say

 NSArray *myArray = @[@"bla", @"bla", @"bla"]; 

In any case, extra nil does not matter in the syntax you provide.

+5
source

When you add nil when creating an NSArray , objects are added before that nil . nil and objects after that are ignored. To complete, you cannot add nil to NSMutableArray either (say using the addObject: method), and this will throw an exception.

you can put [NSNull null]; although when creating an NSArray.

+11
source

Yes, that’s exactly what you can do. Neil after the first will be ignored.

+2
source

Why are you intentionally adding nil to an array? I think you better stop a little and think twice why you should do this. If you are not sure about the size of the array, you can always go with NSMutableArray.

-1
source

Source: https://habr.com/ru/post/1439958/


All Articles