我正在阅读有关 iOS 6 中的 coreImage 的教程。 在那个教程中,我发现了类似的东西:
@implementation ViewController {
CIContext *context;
CIFilter *filter;
CIImage *beginImage;
UIImageOrientation orientation;
}
//Some methods
@end
变量在@implementation 语句后的括号中在.m 文件中声明。我第一次看到这种变量声明。
上面的变量声明和下面的代码有区别吗
@implementation ViewController
CIContext *context;
CIFilter *filter;
CIImage *beginImage;
UIImageOrientation orientation;
//Some methods
@end
最佳答案
有很大的不同。
@interface
之后方括号内的变量或 @implementation
是实例变量。这些是与类的每个实例关联的变量,因此可以在实例方法中的任何位置访问。
如果不放置括号,则声明全局变量。在任何括号 block 之外声明的任何变量都将是全局变量,无论这些变量是在 @implementation
之前还是之后。指示。并且全局变量是邪恶的,需要不惜一切代价避免(你可以声明全局常量,但避免全局变量),特别是因为它们不是线程安全的(因此可能会产生错误乱调试)。
事实上,在历史上(在 Objective-C 和编译器的第一个版本中),您只能在 @interface
之后的括号中声明实例变量。在你的.h
文件。
// .h
@interface YourClass : ParentClass
{
// Declare instance variables here
int ivar1;
}
// declare instance and class methods here, as well as properties (which are nothing more than getter/setter instance methods)
-(void)printIVar;
@end
// .m
int someGlobalVariable; // Global variable (bad idea!!)
@implementation YourClass
int someOtherGlobalVariable; // Still a bad idea
-(void)printIVar
{
NSLog(@"ivar = %d", ivar1); // you can access ivar1 because it is an instance variable
// Each instance of YourClass (created using [[YourClass alloc] init] will have its own value for ivar1
}
只有现代编译器允许您在类扩展(.m 实现文件中的 @interface YourClass ()
)或 @implementation
中声明实例变量(仍在括号中) , 除了可以在 @interface
之后声明它们在你的.h
.好处是通过在 .m 文件中而不是在 .h 文件中声明它们来对类的外部用户隐藏这些实例变量,因为类的用户不需要知道的内部编码细节你的类,但只需要知道公共(public) API。
最后一个建议:Apple 越来越推荐使用 @property
,而不是使用实例变量。直接,并让编译器(显式使用 @synthesize
指令,或隐式使用现代 LLVM 编译器)生成内部支持变量。所以最后你通常根本不需要声明实例变量,因此省略了空的 { }
在@interface
之后指令:
// .h
@interface YourClass : ParentClass
// Declare methods and properties here
@property(nonatomic, assign) int prop1;
-(void)printProp;
@end
// .m
@implementation YourClass
// @synthesize prop1; // That's even not needed with modern LLVM compiler
-(void)printProp
{
NSLog(@"ivar = %d", self.prop1);
}
关于objective-c - Objective-C 中的变量声明差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13514642/