【问题标题】:Do I still need to declare the instance variable if I am using @property?如果我使用@property,我还需要声明实例变量吗?
【发布时间】:2012-01-17 14:25:42
【问题描述】:

在 Objective C 中,您现在可以使用 @property 和 @synthesize 自动生成 get 和 set 方法。我的问题是:我还需要在界面中声明属性吗?没有它,我的程序编译并运行良好。但是大多数书籍和其他示例仍然有它。为什么?

@interface Person : NSObject {
// do i need the declaration "NSString name;"? why?
// i have notice that my program works fine without it.
// but many programming examples still incude it.     
// NSString name;
}
@property NSString *name;
@end

@implementation Person
@synthesize name;
@end

【问题讨论】:

    标签: iphone objective-c ipad ios5 properties


    【解决方案1】:

    这取决于运行时。现代运行时在 iOS 中使用,您不必声明 ivars。但在 OS X 中并非总是如此。看这里 - http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html

    【讨论】:

    • 我认为这是编译器的事情,不会影响运行时。
    • 编译器只知道它为什么运行时编译
    【解决方案2】:

    你说的是ivar。您不需要声明它,因为 @synthesize 会为您添加它。这在旧编译器上并非如此(显然在 @propertiy 被添加到语言之前),因此很多人和书籍仍然这样做。

    PS:如果你没有任何 ivars,你也不需要{...},例如:

    @interface Person : NSObject
    
    @property NSString *name;
    //...
    

    【讨论】:

      【解决方案3】:

      你不需要;将为您生成 ivar。但是调试器不会显示自动生成的 ivars,所以我还是喜欢声明它们。

      【讨论】:

      • 很高兴知道,但很痛苦。重点是消除不必要的打字。
      • 我可以看到 ivars 及其值,就像在 lion 上的 xcode 4.2.1 上调试器中的其他所有内容一样。
      【解决方案4】:

      您不需要声明 ivar。如果您省略 ivar,@synthesize 指令会为您执行此操作。

      【讨论】:

      • 问题标记为iOS5。如果您的目标是 iOS5,这总是正确的。
      • 确实如此,但一个限定词会很好,这样 Mac 开发人员在寻找信息时就不会误读它。
      猜你喜欢
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多