Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you use an underscore for an instance variable, but not its corresponding property? [duplicate]

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

I am new to iphone development.I am doing research on voice recording in iphone .I have downloaded the "speak here" sample program from Apple.It consist of LevelMeter.h file, in which

 @interface LevelMeter : UIView {

CGFloat                     _level, _peakLevel;

   }

The property are set as

 @property                      CGFloat level;
 @property                      CGFloat peakLevel;

What is the use of declaring a varible like _level and setting its property as level.Please explain me.Thanks.

like image 942
Warrior Avatar asked Nov 14 '22 12:11

Warrior


1 Answers

Reminder

The @property directive is equivalent to declaring both a setter and a getter. In the case of level,

@property CGFloat level;

can be replaced by

- (CGFloat)level;
- (void)setLevel:(CGFloat)v;

Your question

Why declare a property named level for a variable named _level and why name a variable with a leading _ in the first place? I don't know.

How it works, is answered in LevelMeter.m:

- (CGFloat)level { return _level; }
- (void)setLevel:(CGFloat)v { _level = v; }
like image 168
mouviciel Avatar answered Dec 26 '22 12:12

mouviciel