Objective-C Literals
前言
The new object literals syntax being introduced into Objective-C in WWDC2012.(新对象
常量语法
在WWDC2012上被引入OC)
(1)Container Literals:容器常量
“The latest clang now has support for container literals in Objective-C. (最新的clang编译期已经支持了OC中的容器常量。)”容器常量语法与现代脚本语言相似,不过OC中以@开头,如下:
@[@{ @"key" : @"obj" }, @{ @"key" : @"obj2" }]
, @[] syntax定义数组,@{}语法定义字典,都只能存OC对象,且nil不能直接出现在里面,否则直接报错;NSSet常量用数组来实现;
(2)Boxed Expressions:@(),一种语法,封装表达式成OC对象。
@(xxx),xxx为表达式,封装结果的类型取决于表达式。值可以为常量,也可以为变量或函数返回值等。xxx为数字时,@(xxx)为NSNumber类型;xxx为C字符串时,如"anywhere",那么@(xxx)类型为NSString;作为一种“抄近道”,如果xxx直接为数字,那么()可以省略,直接@xxx,如@3,变量不能这样。
Applied to strings, this gives us the familiar and ancient construct @"object string".(这就是@"xxx"型字符串的来源!!!)
(3)Initializers:全局变量的初始化
“C has an odd quirk in that any initializer of a global variable must be a compile-time constant. This includes simple expressions, but not function calls.(C语言有一个怪癖:初始化一个全局变量时赋值的必须是一个“编译时期”认可的常量!简单的表达式可以,函数调用的返回值不行!数值表达式、C字符串和OC字符串都是编译期常量,所以都均可)”
int x = 2 + 2; OK!
float y = sin(M_PI); not OK!
//C string literals are compile-time constants, so this is legal:
char *cstring = "hello, world";
//NSString literals are also compile-time constants, so the Cocoa equivalent is legal:
NSString *nsstring = @"hello, world";
“It's important to note that none of the new literal syntax qualifies as a compile-time constant. (请注意:凡是涉及方法调用的都不是编译期常量)”,所以下面是错的:
This is because the @[] syntax literally translates into a call to an NSArray method.
NSArray *array = @[ @"one", @"two" ]; not OK!
另有实验为证:
非编译常量不能初始化全局变量(这是C语言硬性规定的),但可以初始化局部变量!
Conclusion
The new object literals and subscripting syntax in Objective-C can significantly reduce the verbosity of code that deals heavily with arrays and dictionaries. The syntax is similar to that found in common scripting languages, and makes code much easier to read and write, aside from a minor surplus of @ symbols.(OC中的常量和下标语法可以有效地减少数组和字典中冗余的代码。常量语法类似于常见的脚本语言,可以使代码更容易读写,仅以@为代价)