Objective c 应为';:';我的代码中的语法错误

Objective c 应为';:';我的代码中的语法错误,objective-c,Objective C,我的代码如下: NSString *str1 = @"Name"; NSString *str2 = @"Age"; NSArray *array = [[NSArray alloc] initWithObjects: str1, str2 count:2]; 然而,当我构建和运行时,我会抛出一个异常,它说:Expected':'就在count中的'c'之前 为什么会这样?我尝试输入“:”,虽然我知道这在语法上是不正确的,但是Xcode要求我在countinitWithObjects:cou

我的代码如下:

NSString *str1 = @"Name";
NSString *str2 = @"Age";

NSArray *array = [[NSArray alloc] initWithObjects: str1, str2 count:2];
然而,当我构建和运行时,我会抛出一个异常,它说:Expected':'就在
count
中的'c'之前


为什么会这样?我尝试输入“:”,虽然我知道这在语法上是不正确的,但是Xcode要求我在
count

initWithObjects:count:
用于C数组之前用“]”结束。在本例中,您需要在末尾使用
initWithObjects:
nil
参数:

NSString *str1 = @"Name";
NSString *str2 = @"Age";

NSArray *array = [[NSArray alloc] initWithObjects: str1, str2, nil];

如果您刚刚开始学习Objective-C,请使用最近介绍的最方便的方法:

NSArray* array= @[ str1, str2] ;

有关更多详细信息,请参见

是的,我知道这一点,但是我想在开始快捷方式之前了解我所做工作的基本机制。很好的建议,很好。请注意,编译器将文本转换为对您最初尝试的
+[NSArray initWithObjects:count]
的调用。看