Obj-C @synthesize

4
可能重复:
在Objective C中使用下划线前缀属性名 iPhone应用程序开发入门者:
在.h文件中:
@property (nonatomic, retain) IBOutlet UILabel *detailDescriptionLabel;

in .m

@synthesize detailDescriptionLabel = _detailDescriptionLabel;

我习惯于看到

@synthesize detailDescriptionLabel;

= _ 这个让我困惑,它是在做什么?


iOS 5受NDA保护;已进行编辑以避免违反该保密协议。 - bbum
2个回答

6

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


2
请注意,用户代码不应使用前置下划线字符:http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingBasics.html#//apple_ref/doc/uid/20001281-1002931-BBCFHEAB - e.James
2
那是真的。但是,你看过 XCode 4 的界面生成器生成的代码吗?它大多数情况下都会添加下划线。 - Deepak Danduprolu
明白了,谢谢。新的Xcode奇怪的是以前会保持名称不变,但它的默认代码会更改实例变量的名称。 - user544359
@e.James:感谢提供链接,但我读到“在实例变量名前使用下划线字符是允许的”。 - Graham Lea
1
@Graham Lea:是的,自去年以来Apple已经修订了该文档。实例变量前的下划线现在被认为是正常的。 - e.James

0

n .h

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

in .m

@synthesize detailDescriptionLabel = _detailDescriptionLabel;

这行代码意味着类属性"detailDescriptionLabel"将拥有一个命名为"_detailDescriptionLabel"的setter和getter。
如果名称相同,你将会......(缺失上下文无法翻译完整句子)
@synthesize detailDescriptionLabel;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接