Stanley
Stanley

Reputation: 4486

Why use underscores?

The following example illustrates how you might implement a dealloc method for a Person class:

@interface Person : NSObject
@property (retain) NSString *firstName;
@property (retain) NSString *lastName;
@property (assign, readonly) NSString *fullName;
@end

@implementation Person
// ...
- (void)dealloc
    [_firstName release];
    [_lastName  release];
    [super      dealloc];
}
@end

The above is from Apple documentation : memory management example

My question is why there are underscores before firstName and lastName in dealloc?

Upvotes: 2

Views: 159

Answers (3)

MaxGabriel
MaxGabriel

Reputation: 7705

When you do self.firstName you're actually calling the getter firstName (same for self.firstName = @"" calling setFirstName:. Those getter and setter methods actually access the underlying instance variable, like this:

- (NSString *)firstName
{
    return _firstName;
}

When you do _firstName, you're directly accessing the instance variable without going through the setter. The reason that people directly access the instance variable during init and dealloc is that the setter method or an object which is observing[1] the property could then run code. This could be bad, because the object probably hasn't either finished initializing itself (in init), or some of it's properties have been released (in dealloc).

When you write @sythesize firstName = _firstName, you are specifically naming the underlying instance variable _firstName rather than firstName. This way, you don't accidentally type firstName and bypass the setter method & KVO. If you don't write an @synthesize, the compiler automatically names the instance variable _firstName.

Just a personal recommendation -- I would use ARC so that you don't have to deal with dealloc.

[1] Key-Value observing is a way in which an object can register to be notified of changes to a property. It is automatically provided through @synthesize or correctly named getter and setter methods.

Upvotes: 1

Manann Sseth
Manann Sseth

Reputation: 2745

Approach :: By default when you synthesize the getter and setter accessor methods it is assumed that the property and ivar have the same name.

This can make it confusing at first glance as to when you are using the getter/setter methods and when you are accessing the ivar directly.

The alternative is name the ivar differently from the property. A common approach is to use an underscore to prefix the ivars names.

You can Refer this link : http://useyourloaf.com/blog/2011/02/08/understanding-your-objective-c-self.html

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 186098

The properties would typically be synthesized thus:

@synthesize firstName = _firstName, …;

Upvotes: 2

Related Questions