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

主宰稳场 提交于 2019-11-30 15:28:14

The addition of nil to the end is not intended to add nils to an array, its simply an artifact of how C processes ... variable argument lists. It has nothing to do with NSArray or NSMutableArray, you cannot store nil in either.

So whether the compiler accepts, nil, nil, nil is actually irrelevant. The compiler will stop reading at the first nil. And writing that code in the first place 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"];

Either way the extra nils matter not in the syntax you provided.

When you put nil when creating NSArray, objects upto that nil get added. The nil and objects after that are ignored. Just to complete, you can't add nil to NSMutableArray also (say using addObject: method) and doing that will raise exception.

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

Yes, exactly, this can be done. The nils after the first one will be ignored.

Why would you intentionally add nil to an array? I think you'd better stop a bit and think twice about why do you have to do this. If you are unsure about the size of the array, you can always go with NSMutableArray.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!