John Lane
John Lane

Reputation: 1132

iOS Variable names and memory management

I am a bit confused by the underscore naming and the self. Is the following code OK?

@interface MyClass()

@property (nonatomic,retain) NSString        *name;
@property (nonatomic,retain) NSString        *surname;

@end

@implementation MyClass
@synthesize name = _name;
@synthesize surname = _surname;

Then when I need to assign a value I do this

self.name = [someParam retain];

Upvotes: 0

Views: 106

Answers (3)

Abhishek Singh
Abhishek Singh

Reputation: 6166

No this is not right as you have to use the alias _name like

if(_name)
{
    [_name release];
    _name=nil;
}
else
{
    //retain the object
}

Upvotes: 0

rckoenes
rckoenes

Reputation: 69469

No this is not ok, since the self.name will also retain the value as your declared in the property.

This wil retain:

self.name = someParam;

Other way the write then same (be aware to release the current var):

if (_name != someParam) {
    if(_name) {
       [_name release], _name = nil;
    }
    _name = [someParam retain];
}

Upvotes: 2

John Smith
John Smith

Reputation: 1172

you don't have to repeat the retain :)

just:

self.name = someParam;

but for the rest I think it's ok

Upvotes: 1

Related Questions