Apr
17

Objective-C: Properties and Instance Vars Gotcha

Learned an important lesson today regarding properties and instance variables (ivars) in Objective-C today. For example, consider the following interface and implementation:

@interface MyButton : UIButton
{
    NSString *label;
}

@property (nonatomic, copy) NSString *label;

@end

@implementation MyButton

@synthesize label;

@end

Now, inside my button class if I reference label:

label = @"Click Me!";

This directly accesses the ivar (NSString *label) and not the @property. To access the property, you would use self:

self.label = @"Click Me!";

The important thing to note here is that if you access the ivar directly, you are bypassing the getters/setters created by the synthesized property. I was having issues where variables I created were not being retained, and adding "self." solved it, leading me to this realization that I wasn't actually accessing the property. My new style for reminding me when I'm accessing an ivar or property is my old tried-and-true method for differentiating private vars in Actionscript or PHP; the underscore:

@interface MyButton : UIButton
{
    NSString *_label;
}

@property (nonatomic, copy) NSString *label;

@end

@implementation MyButton

@synthesize label=_label;

@end

Check the difference above. I changed the synthesize statement to point to a differently named instance var. So when I access "self.label," it will modify _label through the getter/setter. You can also use _label inside the instance to directly access the ivar.

prev 1 next

Products

Goodies

T1EOS

Content Management System T1EOS: Content Management System

Our customized content management framework T1EOS manages articles, blogs, categories, events, tagging, images & galleries, a Facebook Connect integrated commenting system, and more — all out-of-the-box.

github

ASRA

A Simple Restful API

ASRA is a lightweight package that assists in the rapid development of simple APIs for exporting data for Flash, Flex or other applications.

Download

Plum Dumb

A Typeoneerror TextMate Theme Plum Dumb