使用@ [array,of items] vs [NSArray arrayWithObjects:] [英] Using @[array, of, items] vs [NSArray arrayWithObjects:]
问题描述
两者之间是否有区别
NSArray *myArray = @[objectOne, objectTwo, objectThree];
和
NSArray *myArray = [NSArray arrayWithObjects:objectOne, objectTwo, objectThree, nil];
一个人优先于另一个人吗?
Is one preferred over the other?
推荐答案
它们几乎相同,但不完全相同. Objective-C Literals 上的Clang文档指出:
They are almost identical, but not completely. The Clang documentation on Objective-C Literals states:
数组文字表达式扩展为对
+[NSArray arrayWithObjects:count:]
,它验证所有对象都是 非零.可变格式+[NSArray arrayWithObjects:]
使用nil作为 参数列表终止符,可能导致数组格式错误 对象.
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.
所以
NSArray *myArray = @[objectOne, objectTwo, objectThree];
如果objectTwo == nil
会抛出运行时异常,但是
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.
这篇关于使用@ [array,of items] vs [NSArray arrayWithObjects:]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!