@synthesize 与使用 self [英] @synthesize vs. use of self
问题描述
我是 iOS 新手,一直在从教程和我的教授那里学习.
在 .h
文件中,我们有:
I am new to iOS, and have been learning from tutorials and from my professor.
In the .h
file we have:
@interface ViewController : UIViewController <UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UILabel *myResponse;
@property (strong, nonatomic) IBOutlet UITextField *myInput;
@end
在 .m
文件中,我们有:
In the .m
file we have:
@sysnthesize myResponse
@synthesize myInput
我的问题是:在 .m
文件中,添加 @synthesize
和使用类似 [myInput < 的属性有什么区别;do something here>]
与消除 @synthesize
和使用 [self.myInput <do something here>]
.我在 Xcode 5 上运行,所以我知道我可以使用自动合成,但是两者之间有更细微的区别吗?
My question is this: What is the difference, in the .m
file, between added the @synthesize
and then using the properties like [myInput <do something here>]
versus eliminating the @synthesize
and using [self.myInput <do something here>]
. I am running on Xcode 5, so I do understand that I have auto-synthesize available, but is there a more subtle difference between the two?
我的教授使用了 @synthesize
而我所关注的教程只是使用了 self.propertyName
,因此我很好奇.
My professor used the @synthesize
and the tutorial I was following was just using the self.propertyName
, hence I am curious.
谢谢.
推荐答案
您不再需要显式地将 @synthesize
用于属性.如果您的教授正在使用它,那只是为了明确并展示幕后发生的事情.
You no longer have to explicitly use @synthesize
for properties. If your professor was using it, it was just to be explicit and demonstrate what's happening under the hood.
如果您的属性在 .h 文件中定义,则会自动生成访问器、修改器和实例变量.如果您明确地@synthesize
这些属性,则可以通过指令后提供的任何 ivar 名称访问它们.如果不使用 @synthesize
,自动生成的 ivars 可以通过 _somePropertyName
获得.
If your property is defined in the .h file, accessors, mutators and instance variables are automatically generated. If you explicitly @synthesize
those properties, they are accessible via whatever ivar name is provided after the directive. If @synthesize
is not used, the automatically generated ivars are available through _somePropertyName
.
在您的示例中,使用 @synthesize
,myResponse
UILabel 可通过实例变量 myResponse
访问.如果没有 @synthesize
,它可以通过 _myResponse
获得.在这两种情况下,它都可以通过 self.myResponse
获得.在任何生命周期方法、访问器或修改器(-viewDidLoad
、-viewWillAppear
、-setMyResponse:
等)中使用实例变量是最佳实践) 并在所有其他方法中使用 self.propertyName
来清楚地区分类的属性和实例变量.
In your example, with the @synthesize
, the myResponse
UILabel is accessible through the instance variable myResponse
. Without the @synthesize
, it is available through _myResponse
. In both cases, it is available through self.myResponse
. It's best practice to use the instance variables in any lifecycle methods, accessors, or mutators (-viewDidLoad
, -viewWillAppear
, -setMyResponse:
, etc) and to use self.propertyName
in all other methods to clearly distinguish the properties of a class from the instance variables.
这篇关于@synthesize 与使用 self的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!