简体   繁体   English

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

[英]Objective-C @property and @synthesize best practice

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. 因此,我是Objc-C的新手,我现在正在学习对变量使用@property@synthesize的知识,我想知道接下来应该如何访问变量。 Should I access it through [self var] or self.var or what? 我应该通过[self var]还是self.var或其他方式访问它? 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";
}

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 . 因为你正在访问伊娃直接绕过你的@property,这往往不作,如果你有声明为踏踏实实做这最后一个不好@property
In your case you are changing a property on your iVar, so there is no harm, but if you would do this : 在您的情况下,您正在更改iVar上的属性,因此没有任何危害,但是如果您这样做,则可以:

_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. 一个strong设置者将保留该对象,但是现在没有人保留它,它将消失并且您将得到一个错误的指针,这会使您的应用程序崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM