@符号在Objective-C中代表什么?

时间:2020-03-05 18:42:44  来源:igfitidea点击:

我正在学习Objective-C,并不断碰到@符号。它用于不同的场景,例如,在字符串开头或者用于综合访问器方法。

@符号在Objective-C中是什么意思?

解决方案

回答

来自Objective-C教程:@符号,其原因在于各个关键字的前面:

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 *'。

回答

C或者C ++标识符中不使用'@'字符,因此它以与其他语言的关键字不冲突的方式引入了Objective-C语言关键字。这使语言的"目标"部分可以与C或者C ++部分自由地混合在一起。

因此,除了极少数例外,每当我们在某些Objective-C代码中看到@时,我们都在看的是Objective-C构造而不是C或者C ++构造。

主要例外是id,Class,nil和Nil,即使它们后面也可能带有typedef或者#define,它们通常被视为语言关键字。例如,实际上,编译器确实会根据其应用于声明的指针类型转换规则以及是否生成GC写障碍的决策来特别对待id。

其他例外是​​" in"," out"," inout"," oneway"," byref"和" bycopy";这些用作方法参数和返回类型的存储类批注,以使分布式对象更有效。 (它们成为运行时可用的方法签名的一部分,DO可以查看该签名以确定如何最好地序列化事务。)@property声明,copy,retain,assign中也包含属性。 readonlyreadwritenonatomicgettersetter`;这些仅在" @property"声明的属性部分内有效。

回答

来自Macrumors:Objective-C教程,位于字符串文字前面:

There are also @"" NSString literals. It is essentially shorthand for NSString's +stringWithUTF8String method.

@还为C字符串添加了unicode支持。