我正在学习Objective-C,一直碰到@符号。它在不同的场景中使用,例如在字符串的开头或合成访问器方法。
在Objective-C中,@符号是什么意思?
在C或C++标识符中不使用EDCOX1×0字符,因此它以不与其他语言的关键字冲突的方式引入Objul-C语言关键词。这使得语言的"目标"部分能够自由地与C或C++部分混合。
因此,很少有例外,任何时候在某些Objto-C代码中都可以看到EDOCX1 0,而不是C或C++构造。
主要的例外是id、Class、nil和nil,它们通常被视为语言关键字,尽管它们后面可能也有typedef或#define。例如,编译器实际上确实专门处理id,它应用于声明的指针类型转换规则以及是否生成gc写屏障的决定。
其他例外情况有:in、out、inout、oneway、byref和bycopy,它们被用作方法参数和返回类型的存储类注释,以提高分布式对象的效率。(它们成为运行时提供的方法签名的一部分,可以查看以确定如何最好地序列化事务。)在@property声明、copy、retain、assign、readonly、readwrite、nonatomic、getter和setter中也有属性;这些属性e仅在@property声明的属性部分内有效。
来自Objective-C教程:@symbol,它出现在各种关键字前面的原因是:
Using @ should make it easier to bolt an Objective-C compiler on to an existing C compiler. Because the @ isn't valid in any context in C except a string literal, the tokenizer (an early and simple step in the compiler) could be modified to simply look for the @ character outside of a string constant (the tokenizer understands string literals, so it is in a position to distinguish this). When @ is encountered the tokenizer would put the rest of the compiler in"Objective-C mode." (The Objective-C parser would be responsible for returning the compiler back to regular C mode when it detects the end of the Objective-C code).
同样,当在字符串文本前面看到时,它在C中生成nsstring而不是"char*"。
来自MacRulls:Objective-C教程,当在字符串文本前面时:
There are also @"" NSString literals. It is essentially shorthand for NSString's +stringWithUTF8String method.
@还为C字符串添加了Unicode支持。
从手册中:
Objective-C frameworks typically do not use C-style strings. Instead,
they pass strings around as NSString objects.
The NSString class provides an object wrapper for strings that has all
of the advantages you would expect, including built-in memory
management for storing arbitrary-length strings, support for Unicode,
printf-style formatting utilities, and more. Because such strings are
used commonly though, Objective-C provides a shorthand notation for
creating NSString objects from constant values. To use this shorthand,
all you have to do is precede a normal, double-quoted string with the
@ symbol, as shown in the following examples:
1 2 3
| NSString *myString = @"My String
";
NSString *anotherString = [NSString stringWithFormat:@"%d %@", 1, @"String"]; |