Mik*_*keS 35 gcc objective-c ios
我刚刚了解了在使用GCC编译时可以使用的__unused标志,我了解的越多,我的问题就越多......
为什么编译没有警告/错误?我特意告诉编译器我不会使用变量似乎很奇怪,然后当我使用它时,事情正常进行.
- (void)viewDidLoad
{
[super viewDidLoad];
[self foo:0];
}
- (void)foo:(NSInteger)__unused myInt
{
myInt++;
NSLog(@"myInt: %d", myInt); // Logs '1'
}
Run Code Online (Sandbox Code Playgroud)
另外,以下两种方法签名之间有什么区别?
- (void)foo:(NSInteger)__unused myInt;
- (void)foo:(NSInteger)myInt __unused;
Run Code Online (Sandbox Code Playgroud)
Ali*_*are 77
该__unused宏(这实际上是扩大到__attribute__((unused))GCC属性)只告诉编译器:"如果我不使用这个变量不提醒我".
unused:此属性附加到变量,表示该变量可能未使用.GCC不会对此变量发出警告.(来源:gnu.gcc.org doc)
所以这个GCC属性是为了避免在你不使用变量时发出警告,而在你使用你声称未使用的变量时不要触发.
关于在上一个示例中将变量名称之前或之后放置属性,在您的情况下,两者都被接受并且等效:为了兼容性目的,编译器只是放宽了这个位置(就像你也可以写两个const int i或者int const i)
为了与为嵌套声明符实现属性的编译器版本编写的现有代码兼容,在放置属性时允许一些松弛(来源:gnu.gcc.org doc)
Cœu*_*œur 10
从Xcode 7.3.1开始,目前没有区别:
- (void)foo:(NSInteger)__unused myInt;// [syntax 1]
- (void)foo:(NSInteger __unused)myInt;// [syntax 2]
- (void)foo:(__unused NSInteger)myInt;// [syntax 3]
Run Code Online (Sandbox Code Playgroud)
但以下不起作用:
- (void)foo:(NSInteger)myInt __unused;// [doesn't work]
Run Code Online (Sandbox Code Playgroud)
对于此用法,Apple建议使用第一种语法.(信息部分来自这个答案)
但是有以下区别:
__unused NSString *foo, *bar; // [case a] attribute applies to foo and bar
NSString *foo __unused, *bar; // [case b] attribute applies to foo only
NSString * __unused foo, *bar; // [case c] attribute applies to foo only
NSString __unused *foo, *bar; // [case d] attribute applies to foo and bar
CFStringRef __unused foo, bar; // [case e] attribute applies to foo and bar
Run Code Online (Sandbox Code Playgroud)
如果我们想要__unused应用于所有语法,语法[a]是我个人最好的,因为它没有任何含糊之处.
如果我们想__unused申请一个,语法[b]是我个人最好的,因为它没有任何歧义.
后三种解决方案是可以接受的,但在我看来令人困惑.(信息部分来自这个答案)
| 归档时间: |
|
| 查看次数: |
9003 次 |
| 最近记录: |