In Objective-C on iOS, what is the (style) difference between "self.foo" and "foo" when using synthesized getters?

I have personally settled on using an underscore prefix for ivars, and this kind of synthesize

@synthesize name = _name;

That way I don't mix them up. The major issue with not using self is that this code

_name = ...

is very different from

self.name = ...

When the @property uses the retain option. The first does not retain the object, and the second calls the synthesized setter that retains.

The only time it makes a big difference is with assigning, so I tend to use self. all of the time so I make sure I do it on assigns.


Your point 1 is not quite right: self.soundEffects is not an ivar, although it may happen to give you something which is -- as it does in the case of your synthesized NSArray, at the moment.

This in turn implies that your point 2 is the crux of the matter -- if you route all access through the accessor, then everything is nicely encapsulated and you're free to modify the implementation later without having to worry about side effects.

It's also good practice for when you use the mutator, so you maintain consistent memory management.

For the most part, I'd say it's advisable to route through self.property for everything that is a property, and restrict direct ivar access to things which are strictly internal. However, I'll admit that in some cases -- especially for things that don't use retain/copy semantics -- it can be more of a style preference.


using something like self.variable = nil makes the variable go through its setter and therefore gets memory managed for free. if you just use variable = nil for instance in a dealloc method, it will cause a leak since it is not actually going through the synthesized setter for the variable and decreasing the retain count. See this post memory leak with self.

For this reason, it is advisable (i believe) to always use self. when dealing with instance variables that you own as far as memory management is concerned.


self.soundEffects
sets/gets the instance variable through the setter/getter, and hence if we want to do some custom operations when their value changes, that logic can go in their getter/setter.

Also as per ios 6, the ivar corresponding to

@property (nonatomic)NSArray *propertyName;

will be

_propertyName

so i guess you cant use

id foo = [soundEffects objectAtIndex:1];
anymore.Not sure though.Instead you should use
id foo = soundEffects[1];