{}内的objective-c变量声明与@interface和@end之外的声明

时间:2022-06-11 19:58:08

Please can any one tell me whats the difference between declaring a variable inside { } vs outside of @interface & @end in header file. Both ways lead to successful compilation.

请问任何人告诉我在{}内部变量与@interface之外的变量和头文件中的@end之间的区别。两种方式都可以成功编译。

2 个解决方案

#1


5  

if you want the variable to be part of the class (a.k.a. instance variable) then you declare it inside the brackets, otherwise it is declared as a global variable which has nothing to do with the class.

如果你想让变量成为类的一部分(a.k.a。实例变量),那么你在括号内声明它,否则它被声明为一个与该类无关的全局变量。

e.g.

// XYZ.h

@interface XYZ
{
  int myinstancevariable;
}
@end

int myglobalvariable;

...

XYZ* a = [[XYZ alloc] init];
NSLog(@"%d", [a myinstancevariable]);
NSLog(@"%d", myglobalvariable );

edit: forgot {}

编辑:忘了{}

#2


1  

If you declare a variable inside a code block - {} it's scope (lifespan) is inside that block only.

如果在代码块中声明一个变量 - {}它的范围(生命周期)仅在该块内。

If you declare it outside @interface & @end it's scope is inside that file. If this would be a header file this variable could be used globally.

如果你在@interface和@end之外声明它的范围就在那个文件里面。如果这是头文件,则可以全局使用此变量。

#1


5  

if you want the variable to be part of the class (a.k.a. instance variable) then you declare it inside the brackets, otherwise it is declared as a global variable which has nothing to do with the class.

如果你想让变量成为类的一部分(a.k.a。实例变量),那么你在括号内声明它,否则它被声明为一个与该类无关的全局变量。

e.g.

// XYZ.h

@interface XYZ
{
  int myinstancevariable;
}
@end

int myglobalvariable;

...

XYZ* a = [[XYZ alloc] init];
NSLog(@"%d", [a myinstancevariable]);
NSLog(@"%d", myglobalvariable );

edit: forgot {}

编辑:忘了{}

#2


1  

If you declare a variable inside a code block - {} it's scope (lifespan) is inside that block only.

如果在代码块中声明一个变量 - {}它的范围(生命周期)仅在该块内。

If you declare it outside @interface & @end it's scope is inside that file. If this would be a header file this variable could be used globally.

如果你在@interface和@end之外声明它的范围就在那个文件里面。如果这是头文件,则可以全局使用此变量。