What does the @ symbol represent in objective-c?
我正在学习Objective-C,一直碰到@符号。它在不同的场景中使用,例如在字符串的开头或合成访问器方法。
在Objective-C中,@符号是什么意思?
在C或C++标识符中不使用EDCOX1×0字符,因此它以不与其他语言的关键字冲突的方式引入Objul-C语言关键词。这使得语言的"目标"部分能够自由地与C或C++部分混合。
因此,很少有例外,任何时候在某些Objto-C代码中都可以看到EDOCX1 0,而不是C或C++构造。
主要的例外是
其他例外情况有:
来自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"];