views:

271

answers:

3

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.

+1  A: 

Here is the link which will give you some more details about accessors and their benefits: http://www.seattlexcoders.org/shared/AccessorTalk.pdf

Manjunath
+1  A: 

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; }
mouviciel
Thanks Now i am clear.
Warrior
The reason to add an underscore to the ivar is just to make the difference between ivar and property clearer in code. Apple seems to use this style pretty extensively. You do not necessarily have to write the accessor methods yourself: `@synthesize level = _level;` will make an automatic connection between the two.
Ole Begemann
The other reason to name the ivar `_level` and the property `level` is that, if you named the property `_level`, the getter would have a leading underscore, which violates Apple's style recommendations: http://developer.apple.com/iphone/library/documentation/cocoa/conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-1003829 Apple reserves methods with leading underscores for internal Cocoa/Cocoa-Touch use. Sample code should represent what *you* might write, so it makes sense for Apple to obey the third-party rule in samples.
Peter Hosey
A: 

The underscore represents stuff that should only be accessed from within its own class. Thus, the instance variable shouldn't be accessed from outside the class, but the property can be.

Amorya