Mason
Mason

Reputation: 7103

Question about releasing object with @property @synthesize

I know many similar questions have been asked, which is why I hesitated to post this at all, but I couldn't find anything that answered my question exactly:

When I use @property and @synthesize, does @synthesize take care of releasing the original value for the object being set? I.e. if I have:

@interface SomeClass:NSObject
{
    NSObject *object;
}

@property (nonatomic, retain) NSObject *object;
@end

@implementation SomeClass
@synthesize object;
@end

Is this equivalent to getting a setter method that looks like this?

-(void)setObject:(NSObject *)newObject
{
[object release];
object = [newObject retain];
}

Or do I have to somehow take care of releasing the original object myself?

Thanks for the clarification!

Upvotes: 0

Views: 106

Answers (2)

gsempe
gsempe

Reputation: 5499

The answer is yes. Setter and getter are generated for you and are well done to keep you away from memory management:

-(void)setObject:(NSObject *)newObject {
  if (object != newObject) {
    [object release];
    object = [newObject retain];
  }
}

To release your object you can call:

[self setObject:nil];

Upvotes: 2

Johan Kool
Johan Kool

Reputation: 15927

No need to release the original object yourself, however, you need to still clean things up in -dealloc.

Upvotes: 1

Related Questions