0

Possible Duplicate:
Prefixing property names with an underscore in Objective C

When synthesizing properties I found out that someone is doing:

@synthesize myVar = _myVar;

what is "_myVar" and which is the difference with simply doing :

@synthesize myVar;        

Lastly when I should prefer the first solution to the last one?

Thanks Luca

Community
  • 1
  • 1
luca
  • 36,606
  • 27
  • 86
  • 125

3 Answers3

2

What _myVar really is in your example, is the name of the ivar that is backing your property. By default, when you synthesize a property, an ivar of the same name is created for you. So, you can use your property to set your ivar through setter/getter or the _myVar to directly access your variable (bypassing KVC/KVO of course).

EDIT: From Apple's Coding Guidelines for Cocoa

...In many cases, when you use a declared property you also synthesize a corresponding instance variable.

Make sure the name of the instance variable concisely describes the attribute stored. Usually, you should not access instance variables directly, instead you should use accessor methods (you do access instance variables directly in init and dealloc methods). To help to signal this, prefix instance variable names with an underscore (_)...

Alladinian
  • 34,483
  • 6
  • 89
  • 91
  • when should I use the auto-synthetized ivar and when Should I manually set the backing ivars variable manually? – luca May 18 '12 at 12:07
  • It's really up to you. Though, it's a common practice in obj-c to prefix ivars with an underscore so to make it clear that you're intentionally accessing directly the ivar. If anyone can think of another reason, I would be glad to be enlightened as well. – Alladinian May 18 '12 at 12:20
-1

If you want to use some existing data member in setter and getter then it can be specify like that.

e.g. @synthesize personName=pName;

by this we can use pName instead of personName as per our convenience.

V-Xtreme
  • 7,230
  • 9
  • 39
  • 79
-1

It the name of the private variable.

Se my answer on an other post: answer

Community
  • 1
  • 1
Justin
  • 2,960
  • 2
  • 34
  • 48