Wednesday, October 7, 2009

Properties vs Instance variables

So being able to work with properties in Objective-C is very nice but there are subtle things to keep in mind when using them.

I just came across a problem which cost me about 30 mins of my time. In one of my methods I was (supposedly) assigning an object to one of my properties. The property was marked with retain so that it was supposed to be retained unless re-assigned or the owning object is dealloc'ed. Unfortunately, in a different part of the code, accessing that very property threw an exception.

Turns out that I hadn't yet mastered the subtle difference between properties and instance variable. Assume the following code sample:

@interface Foo : NSObject {
NSString* bar;
}
@property (retain) NSString* bar;
- (void) test;
@end

@implementation Foo {
@synthesize bar;

- (void) test {
NSString* str = @"Test";

// this assignment does not use the synthesized setter
// but accesses the instance variable directly
bar = str;

// same here
self->bar = str;

// only this way of accessing uses the setter and thus
// retains the object reference
self.bar = str;
}
}

First of all I did not know about the arrow-way of accessing instance variables, secondly I thought access as displayed in the first assignment would use the setter method.

Hope this helps in case you're ever going to scratch your head because of this!

No comments:

Post a Comment