Search code examples
objective-cpropertiesretainself

When to access properties with 'self'


I have read a number of questions on this site about this issue, I understand the following:

self.property accesses the getter/setter method created manually or by @synthesize. Depending upon whether the property is declared as retain, copy etc. the retain count is modified correctly, for example a retained property, releases the previous value assigned the new value with 'retain' and increments the retain count by 1.

Properties are usually declared with instance variables of the same name (can be different if you make the assignment manually). This is generally because the @synthesize generated accessors use the instance variable to reference the object in memory and then perform the relevant commands.

My question is based on the fact that in many examples, self.property and property are used interchangeably for different things and I'm having troubles determining the rules. One example in the 'Recipes' example app in the Apple Docs, has the following:

self.navigationItem.title = recipe.name;
nameTextField.text = recipe.name;    
overviewTextField.text = recipe.overview;    
prepTimeTextField.text = recipe.prepTime; 

and...

self.ingredients = sortedIngredients;

Each of these properties have associated private instance variables of the same name. All are declared in the same way with 'nonatomic, retain' attributes. Each are released in dealloc...

Yet 'ingredients' is accessed through self and 'prepTimeTextField' is accessed directly.

What is the reason for the difference in access methods?

What about if I'm accessing a view's delegate? Or a core-data object which was passed to a view controller by it's previous view controller as a retained property?

Many thanks


Solution

  • you almost always want to access variables using the synthesized setters/getters, even if you aren't doing anything special with them at the moment.

    if as your application develops, you find that you need to be doing further validation/formatting of variables, then you can just implement the required setter/getter method, and if you have used the synthesised methods this code will get called.

    this is generally a good habit to get into.