0

Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?

I am beginner in ios app development.I looked over many tutorial and i came across following line

.h file contains:

@property (strong) ScaryBugData *data;

.m contains:

@synthesize data = _data; 

But I am not getting meaning of data = _data. why this is required or what it means.

ref : http://www.raywenderlich.com/1797/how-to-create-a-simple-iphone-app-tutorial-part-1

Community
  • 1
  • 1
subhash kumar singh
  • 2,716
  • 8
  • 31
  • 43
  • And here's another 16: http://stackoverflow.com/q/5582448/ http://stackoverflow.com/q/6049269/ http://stackoverflow.com/q/2371489/ http://stackoverflow.com/q/7174277/ http://stackoverflow.com/q/5659156 http://stackoverflow.com/q/837559/ http://stackoverflow.com/q/6146244/ http://stackoverflow.com/q/10651535/ http://stackoverflow.com/q/6124109/ http://stackoverflow.com/q/8145373/ http://stackoverflow.com/q/3521254/ http://stackoverflow.com/q/6064283/ http://stackoverflow.com/q/9696359/ http://stackoverflow.com/q/5521499/ http://stackoverflow.com/q/5466496/ http://stackoverflow.com/q/2114587/ – jscs Jul 09 '12 at 18:13

2 Answers2

2

_data is the name of the instance variable that is automatically created for you.
data is the name of the property that has a getter and setter.

If you don't specify a custom ivar name it will just default to the name of the property.

In this case you can directly set the ivar using _data = [ScaryBugData data], or you can use the setter using self.data = [ScaryBugData data]. The same goes for getting.

The synthesized setter will make sure the old value is properly released, the new value is properly retained and some more stuff under the hood.

Rengers
  • 14,911
  • 1
  • 36
  • 54
1

If you access self.data, you are calling the getter/setter method. If you assign _data, you are bypassing the setter method and directly access the variable. This could be useful for example if your setter or getter is doing other things that you may not want to in this particular case.

In the Java world, this is equivalent to calling this.thing=xyz vs. setThing(xyz)

Look at the Core Data template for example, and you can see how the managedObjectContext accessor for example is doing extra work, other than just getting the variable.

mprivat
  • 21,582
  • 4
  • 54
  • 64