5

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

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

as the first nil marks array end and two nils after will be ignored?

I got two opposite answers and will try it out.

update:

The reason why I need to do this, is I need to create an UIAlertView, which may have buttons: 'OK' only, or 'Call' and 'Cancel', so either 'OK' or 'Cancel', is the cancel button, whereas 'Call' is other buttons in one case, in other cases, I do not need any other buttons, that's why I need to do this.

1
  • you know, for UIAlertView as you say you need it for, you can just add buttons individually using addButtonWithTitle: Commented Oct 17, 2012 at 0:26

4 Answers 4

12

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.

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

1 Comment

We can add [NSNull null] in NSMutableArray also
5

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.

1 Comment

Yes but actually I am using this for UIAlertView when adding other buttons, so I have either ["Call" "Cancel"] or just ["OK"], so I check: otherButtons: (canMakeCall? "Call" : "OK"), (canMakeCall ? "Cancel" : nil), nil.
2

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

Comments

-1

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.

1 Comment

OP is not, as the other two answers explain, adding nil to the array. Neither NSArray nor NSMutableArray can contain nil.

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.