Objective-C @property 和 @synthesize 最佳实践
所以我是 Objc-C 的新手,我刚刚学习如何使用 @property
和 @synthesize
变量,我想知道如何访问该变量。我应该通过 [self var]
或 self.var
还是其他方式访问它?这用代码演示了我的问题:
@property (nonatomic, strong) UILabel *lbl;
...
@synthesize lbl = _lbl;
-(void) doStuff
{
// How should I acces label?
_lbl.text = @"A";
[self lbl].text = @"B";
self.lbl.text = @"C";
}
So I'm new to Objc-C and I'm just now learning about using @property
and @synthesize
for variables and I was wondering how I should then access the variable. Should I access it through [self var]
or self.var
or what? This demonstrates my question with code:
@property (nonatomic, strong) UILabel *lbl;
...
@synthesize lbl = _lbl;
-(void) doStuff
{
// How should I acces label?
_lbl.text = @"A";
[self lbl].text = @"B";
self.lbl.text = @"C";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里没有区别:
但是您的示例中有一个区别:
最后一个不好,因为您直接绕过 @property 访问 iVar,如果您将其声明为 <,这通常没有意义。代码>@property。
在你的情况下,你正在改变你的 iVar 上的属性,所以没有什么害处,但如果你这样做:
那会给你带来一个大问题,因为你会绕过“setter”。一个
strong
setter 会保留该对象,但现在它不再被任何人保留,它会消失,并且您将得到一个错误的指针,这可能会使您的应用程序崩溃。There is no difference here :
But there is a difference here in your sample :
That last one is not good because you are accessing the iVar directly bypassing your @property, which often don't make sense to do if you have declare it as
@property
.In your case you are changing a property on your iVar, so there is no harm, but if you would do this :
that would cause you a big problem, because you would have bypass the "setter". A
strong
setter would have retain that object, but now it's retain by no one, it will go away and you will have a bad pointer, that can make your application crash.