Question

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";
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top