2012-10-23 32 views
0

我的代码如下:预期“:”在我的代码语法错误

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

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

然而,当我建立&运行我得到一个异常抛出它说:预期“:”中的“C”前右count

这是为什么?我试过输入':',尽管我知道这在语法上不正确,然后Xcode要求我在count之前用']'关闭。

回答

4

initWithObjects:count:用于C数组。在你的情况,你会希望在年底使用initWithObjects:nil说法:

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

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

如果你刚开始学习Objective-C,只是使用最近推出的最方便的方法:

NSArray* array= @[ str1, str2] ; 

有关更多详细信息,请参阅What are the details of "Objective-C Literals" mentioned in the Xcode 4.4 release notes?

+0

是的我意识到这个字面意思,但是我想了解我在开始简化之前所做的基本机制。伟大的建议,但。 – Ryan

+0

太好了。请注意,编译器会将文字转换为您最初尝试使用的'+ [NSArray initWithObjects:count]'的调用。请参阅http://clang.llvm.org/docs/ObjectiveCLiterals.html – Yuji