Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Xcode 4 auto-generate a instance variable?

I'm coming from C# development and just started to learn Objective-C and Xcode 4. As far as I understand "@synthesize" is replacing getter/setter methods for properties if you don't need to check/control the values which are being read or written.

But why does Xcode 4 create a instance variable for me automatically?

Wouldn't this be enough:

@synthesize myProperty;

instead of:

@synthesize myProperty = _myProperty;

?

Why would I want to use/have the instance variable instead of the actual property if I don't have/need any getters or setters?

Thanks in advance!

MemphiZ

EDIT:

I understand that @synthesize is replacing getters/setters but what is this part good for: = _myProperty;? Why would I want to have a instance variable if I could use "myProperty" directly? I would understand using "_myProperty" if the setter for example would check for a condition of the value. If I then want to skip this check I would use _myProperty. But as I use @synthesize I don't have a setter in place that does some check. So why do I have/want an instance variable then?

ANSWER:

See the comments in MattyG's post!

like image 995
MemphiZ Avatar asked Nov 07 '11 02:11

MemphiZ


1 Answers

This is a convention used to remind the programmer to access the instance variables through the setters and getters with self. So if you're using:

@synthesize myProperty = _myProperty;

Then to access the variable directly you must write:

_myProperty = something;

To access the variable through it's setter you must write:

self.myProperty = something;

The benefit is that if you forget to access through self. then the compiler will warn you:

myProperty = something;  //this won't compile

See this also this Question.

like image 185
MattyG Avatar answered Nov 04 '22 06:11

MattyG