2

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

I'm currently learning Objective-C and I'm following a tutorial that uses variables a little funny (to me at least!).

Basically, class variables are declared like this:

         @interface .. { 
            UITextField *_titleField;
            UIImageView *_imageView;
         }

@property (retain) IBOutlet UITextField *titleField;
@property (retain) IBOutlet UIImageView *imageView;

and then synthesized like this:

@synthesize titleField = _titleField;
@synthesize imageView = _imageView;

So basically, whats the purpose of this?

Community
  • 1
  • 1
user339946
  • 5,961
  • 9
  • 52
  • 97

3 Answers3

1

titleField is the synthesized property and _titleField is the backing field for it.

Maybe http://mutelight.org/articles/the-objective-c-retain-property-pattern will help you understand it better

parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
1

Often people use the _ character as a marker for an instance variable (a.k.a. in other languages a ‘field’, or ‘member’, etc). Some people put an underscore after the variable name, some people put it before, some people don't use it at all, some people use different prefixes. The idea is that it helps you distinguish at a glance what are instance variables and what aren't.

Of course, if you do decide to name your instance variables in a particular way, but still want your properties to have ‘normal-looking’ names, you need to map the ‘normal-looking’ name to the ‘instance variable’ name.

dreamlax
  • 93,976
  • 29
  • 161
  • 209
0

A property is just a marker for a pair of methods - 'foo' and 'setFoo' (unless the property is readonly, in which case only 'foo' will by synthesized). A variable (those are instance, not class variables, BTW) is the actual memory store. Properties can be associated with a memory store - this is what @synthesize does - but don't have to. The point being, properties and instance variables often go together but are distinct.

Vladimir Gritsenko
  • 1,669
  • 11
  • 25