Objective-C @property 和 @synthesize 最佳实践

发布于 2024-12-26 07:05:34 字数 398 浏览 0 评论 0原文

所以我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静赏你的温柔 2025-01-02 07:05:34

这里没有区别:

UILabel * l = [self lbl];  // ==   UILablel *l = self.lbl;
[self setLbl:l];          //  ==   self.lbl = l;

但是您的示例中有一个区别:

_lbl.text = @"A";  

最后一个不好,因为您直接绕过 @property 访问 iVar,如果您将其声明为 <,这通常没有意义。代码>@property。
在你的情况下,你正在改变你的 iVar 上的属性,所以没有什么害处,但如果你这样做:

_lbl = [[[UILabel alloc] initWithFrame:aRect] autorelease];

那会给你带来一个大问题,因为你会绕过“setter”。一个strong setter 会保留该对象,但现在它不再被任何人保留,它会消失,并且您将得到一个错误的指针,这可能会使您的应用程序崩溃。

There is no difference here :

UILabel * l = [self lbl];  // ==   UILablel *l = self.lbl;
[self setLbl:l];          //  ==   self.lbl = l;

But there is a difference here in your sample :

_lbl.text = @"A";  

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 :

_lbl = [[[UILabel alloc] initWithFrame:aRect] autorelease];

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文