Syntax for accessing instance variables? (Objective-C)

SpacePyro picture SpacePyro · Jun 15, 2011 · Viewed 9k times · Source

What is the proper syntax for accessing an instance variable in Objective-C?

Assume we have this variable:

@interface thisInterface : UIViewController {
    NSMutableString *aString;
}

@property (nonatomic, retain) NSMutableString *aString;

and that it is synthesized.

When we want to access it, we first would want to allocate and initialize it. Having programmed in Objective-C for about a month now, I've seen two different forms of syntax. I've seen people do simply aString = [[NSMutableString alloc] initWithString:@"hi"], where they allocate the string like that; I've also seen people start it off with self.aString and then they proceed to initialize their ivar. I guess I'm just trying to figure out what is the most proper way of initializing an instance variable, because with the former example, I have received EXC_BAD_ACCESS errors from it. After prepending the self. though, it didn't appear.

Forgive me if this is a duplicate question, but after reading some posts on SO, it's made me curious. I'm trying to learn the proper syntax with Objective-C because I prefer being proper rather than sloppy.

Answer

Steve N picture Steve N · Jun 15, 2011

If you have declared a property and @synthesize it in the .m file, you simply set it like this:

self.aString = @"hi"; // or [[NSMutableString alloc] initWithString:@"hi"];

Using self.varName takes advantage of what your property declaration actually does- it handles retention of the new value (since your property has the retain attribute), releasing the old value, etc for you.

If you just do:

aString = someValue;

... you may be leaking the original value that was in aString, since without using self.aString you are accessing the variable directly vs through the property.