Why does NSArray arrayWithObjects require a terminating nil?

前端 未结 6 832
时光取名叫无心
时光取名叫无心 2020-12-03 01:29

I understand that it marks the end of a set of varargs, but why can\'t it be implemented in such a way that doesn\'t require the nil?

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 02:32

    The simple reason is that behind the scene it's a for-loop that will continue to take arguments, from the va_list till it reaches nil. So the end condition could have been anything, for example the string "stop". But nil is actually quite smart.

    Let's say we have three objects hansel, gretel and woodcutter and create an array of them:

    NSArray *startCharacters = [NSArray arrayWithObjects:hansel, gretel, woodcutter, nil];
    

    Now, we realize that woodcutter never was initiated, so it's nil, but startCharacters will still be created with the hansel and gretel objects, since when it's reaches woodcutter it terminates. So the nil-termination in arrayWithObjects: prevents the app from crashing.

    If you don't like to write out nil you could always create an array like this:

    NSArray *startCharacters = @[hansel, gretel, woodcutter];
    

    It's valid, it's shorter, but it will crash if an object is nil. So the conclusion is that arrayWithObjects: can still be very useful and you can use it to your advantage.

提交回复
热议问题