Objective-C中的变量声明差异

Mid*_* MP 6 variables objective-c

我正在阅读iOS 6中关于coreImage的教程.在那个教程中,我找到了类似的东西:

@implementation ViewController {
    CIContext *context;
    CIFilter *filter;
    CIImage *beginImage;
    UIImageOrientation orientation;
}
//Some methods
@end
Run Code Online (Sandbox Code Playgroud)

变量在@implementation语句后的括号中的.m文件中声明.我第一次看到这种变量声明.

上述变量声明和以下代码之间是否有任何区别

@implementation ViewController

    CIContext *context;
    CIFilter *filter;
    CIImage *beginImage;
    UIImageOrientation orientation;

//Some methods

@end
Run Code Online (Sandbox Code Playgroud)

Ali*_*are 21

这是个很大的差异.

括号内的变量后直接@interface或者@implementation实例变量.这些变量与您的类的每个实例相关联,因此可以在实例方法的任何位置访问.

如果不放括号,则声明全局变量.在任何括号块之外声明的任何变量都将是一个全局变量,无论这些变量是在@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
}
Run Code Online (Sandbox Code Playgroud)

只有现代的编译器让你(括号内仍然)声明实例变量也在里面无论是你的类扩展(@interface YourClass ()在您的m执行文件),或在您的@implementation,除了可能性后宣布他们@interface在你的.h.通过在.m文件中而不是在.h文件中声明它们来将这些实例变量从类的外部用户隐藏起来的好处,因为您的类的用户不需要知道内部编码细节你的班级,但只需要知道公共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);
}
Run Code Online (Sandbox Code Playgroud)