Using @[array, of, items] vs [NSArray arrayWithObjects:]

拟墨画扇 提交于 2019-11-26 17:14:54

问题


Is there a difference between

NSArray *myArray = @[objectOne, objectTwo, objectThree];

and

NSArray *myArray = [NSArray arrayWithObjects:objectOne, objectTwo, objectThree, nil];

Is one preferred over the other?


回答1:


They are almost identical, but not completely. The Clang documentation on Objective-C Literals states:

Array literal expressions expand to calls to +[NSArray arrayWithObjects:count:], which validates that all objects are non-nil. The variadic form, +[NSArray arrayWithObjects:] uses nil as an argument list terminator, which can lead to malformed array objects.

So

NSArray *myArray = @[objectOne, objectTwo, objectThree];

would throw a runtime exception if objectTwo == nil, but

NSArray *myArray = [NSArray arrayWithObjects:objectOne, objectTwo, objectThree, nil];

would create an array with one element in that case.




回答2:


No. At compile time the @[...] literals will be changed to arrayWithObjects:

The only difference is that @[...] is only supported in newer versions of the LLVM compiler.



来源:https://stackoverflow.com/questions/14527489/using-array-of-items-vs-nsarray-arraywithobjects

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