【问题标题】:Obj-C @synthesize [duplicate]Obj-C @synthesize [重复]
【发布时间】:2011-09-13 03:25:26
【问题描述】:

可能重复:
Prefixing property names with an underscore in Objective C

这里是 iPhone 应用开发初学者:

在.h中

@property (nonatomic, retain) IBOutlet UILabel *detailDescriptionLabel;

在.m

@synthesize detailDescriptionLabel = _detailDescriptionLabel;

习惯了

@synthesize detailDescriptionLabel;

= _ 让我失望了,这是在做什么?

【问题讨论】:

标签: iphone objective-c xcode


【解决方案1】:

每个属性都由一个实例变量支持。该语言允许它们以不同的方式命名。通过执行@synthesize detailDescriptionLabel = _detailDescriptionLabel;,您基本上是在说使用_detailDescriptionLabel 作为属性detailDescriptionLabel 的支持实例变量。如果你只是做@synthesize detailDescriptionLabel;,它会隐式理解实例变量具有相同的名称。

【讨论】:

  • 请注意,用户代码不应使用前面的下划线字符:developer.apple.com/library/mac/documentation/Cocoa/Conceptual/…
  • 确实如此。但是,您是否看过 XCode 4 的界面生成器生成的代码。大多数情况下它确实添加了下划线。
  • 知道了。谢谢。奇怪的是,新的 Xcode 用于保持名称相同,但它的默认代码更改了实例变量的名称
  • @e.James:感谢您的链接,但我读到“允许使用下划线字符作为实例变量名称的前缀”。
  • @Graham Lea:是的,Apple 自去年以来已经修改了该文件。实例变量前面的 undersocre 现在被认为是正常的。
【解决方案2】:

n.h

    UILabel *_detailDescriptionLabel;
}
    @property (strong, nonatomic) IBOutlet UILabel *detailDescriptionLabel;

在.m

@synthesize detailDescriptionLabel = _detailDescriptionLabel;

这行意味着属性“detailDescriptionLabel”将有一个名为“_detailDescriptionLabel”的类属性的setter和getter

如果名称相同,您将拥有

@synthesize detailDescriptionLabel;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-16
    • 2012-02-09
    • 2015-08-23
    • 2014-09-11
    • 2010-09-27
    • 2019-10-07
    • 2013-11-29
    • 2011-08-16
    相关资源
    最近更新 更多