【问题标题】:Variable declaration difference in Objective-CObjective-C 中的变量声明差异
【发布时间】:2012-11-22 14:20:21
【问题描述】:

我正在阅读有关 iOS 6 中 coreImage 的教程。 在那个教程中,我发现了类似的东西:

@implementation ViewController {
    CIContext *context;
    CIFilter *filter;
    CIImage *beginImage;
    UIImageOrientation orientation;
}
//Some methods
@end

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

上面的变量声明和下面的代码有什么区别

@implementation ViewController

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

//Some methods

@end

【问题讨论】:

  • 请重新标记它..这是特定于语言的,而不是特定于 ios ios5 xcode4.5 ......这也是 objC 和 C++ 的工作方式(ios1-6)
  • @Daij-Djan: 好的 :) 我在 iOS 6 中看到了这个功能,所以我添加了这个标签。
  • @Daij-Djan 我很确定“@implementation 内的 ivar 块”选项(而不是 @interface)是几年前才添加的。
  • Op 在实现中没有 ivars。没有花括号。并且始终支持静态变量
  • @Daij-Djan:没有花括号???你能检查一下第一个代码 sn -p 吗?

标签: objective-c variables


【解决方案1】:

有很大的不同。

紧跟在@interface@implementation 之后的括号内的变量是实例变量。这些是与您的类的每个实例相关联的变量,因此可以在您的实例方法中的任何位置访问。

如果不加括号,则声明全局变量。在任何括号块之外声明的任何变量都是全局变量,无论这些变量是在 @implementation 指令之前还是之后。而且全局变量是邪恶的,需要不惜一切代价避免(您可以声明全局常量,但避免使用全局变量),尤其是因为它们不是线程安全的(因此可能会产生麻烦调试)。


事实上,从历史上看(在 Objective-C 和编译器的第一个版本中),您只能在 .h 文件中的 @interface 之后的括号中声明实例变量。

// .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
}

除了可以在@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);
}

【讨论】:

  • 感谢您的详细回答 +1
【解决方案2】:

这是一种声明私有变量的方式,它们在类外不可见,也不显示在头文件中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    相关资源
    最近更新 更多