Fourj
Fourj

Reputation: 1897

When declare a property(retain) in objective c, what's the default implementation of set/get method

I am a newer to objective c. I have read the memory management document on apple's "Memory Management Rules". But I am still not very clear about how to manage reference for a property.

What's the default implementation of set/get access methods for a property declared with "retain" annotation?

This is my assuming, please give some comments. Thanks.

@interface SubClass : NSObject {
NSString * _name;
}
... ...
@property (nonatomic, retain) NSString * name;
... ...
@end

-(NSString *) setName {
   return _name;
}

-(void) setName: (NSString *) pName{
    // the correct version of default set method for retain
    if( _name != pName ) {
        [_name release];
        _name = [pName retain];
    }

}

So the dealloc method, is this ok?

- (void)dealloc {
    self.name = nil; // or [_name release], _name = nil;

}

Upvotes: 0

Views: 2014

Answers (3)

BoltClock
BoltClock

Reputation: 723598

As Matteo Alessani says, you can simply synthesize the property to get the default implementations.

For reference, this is what's generated (I got this from reading Objective-C Declared Properties and piecing information together):

- (NSString *)name {
    return _name;
}

- (void)setName:(NSString *)aName {
    if (_name != aName) {
        [_name release];
        _name = [aName retain];
    }
}

Upvotes: 4

Vladimir
Vladimir

Reputation: 170839

As Matteo said you can synthesize accessor methods automatically.

But speaking about implementation details:

  1. yes getter method may look like (but note the correct name):

    -(NSString *) name {
       return _name;
    }
    

    or to handle the case when you use name value and object that holds it gets deallocated:

    -(NSString *) name {
       return [[_name retain] autorelease];
    }
    
  2. setter method:

    -(void) setName: (NSString *) pName{
        NSString *temp = [pName retain];
        [_name release];
        _name = temp;
    }
    
  3. dealloc. Your implementation is ok, but as calling properties may cause some side effects relying that all fields in your object are valid (which may not be so in dealloc method) it may be better to release ivar directly.

Your setter example is wrong as you don't need to handle nil case (actually in your code you can never set name value to nil), but you need to handle the case when property is set to the same object.

Upvotes: 0

Matteo Alessani
Matteo Alessani

Reputation: 10412

You can use synthesize in your implementation file:

@implementation SubClass

@synthesize name = _name;

@end

Automatically you get the default getter and setter.

Upvotes: 2

Related Questions