Confusion on page 72


#1

Hi guys,

I am a little confused on the statement made on page 72 and wondered if anyone would be able to provide a code sample as an example:

The book says: “Finally, you don’t even need an instance variable at all. When you synthesize a property, the compiler looks for an instance variable of the same name and if it finds one, it uses that instance variable, If a matching instance variable is not found, one is automatically created for you.”

I am a little bit confused on what exactly that means. Can anyone provide a code sample showing this?


#2

Typically, you declare an instance variable in the header file:

@interface MyClass : NSObject
{
     int myInstanceVariable;
} 

However, when you declare a property and synthesize it, it automatically creates the instance variable, so you don’t need to put it in the curly brackets.

@interface MyClass : NSObject
{
     
} 
@property (nonatomic, assign) int myInstanceVariable;

Keep in mind: this only works if you synthesize a property. If you write the accessor methods for the property yourself, you do not get the instance variable.