Zhen
Zhen

Reputation: 12431

Objective C: Query about releasing instance property

I have a general query regarding memory management

//In .h file I defined a property
@interface AClass
{
    someClass *aProperty;
}

@property (nonatomic, retain) someClass *aProperty;

end



//In .m file I synthesized the property and also initialized the property
@implementation AClass

-(void)aMethod
{
    self.aProperty = [[someClass alloc]init];
}

My question is

For 'aProperty', where do I do a 'release' to prevent a memory leak? I understand normally for instance properties (using dot notations), we do a release in the 'dealloc' and 'viewdidunload' methods. But for this instance, do I need to release aProperty again within the method 'aMethod'?

Upvotes: 1

Views: 122

Answers (2)

Gobra
Gobra

Reputation: 4261

  1. You must release the instance in the dealloc
  2. Your property initializations leaks the memory. You do alloc+init, retain inside the property, but don't release. Something like self.property = [[[someClass alloc] init] autorelease] is usually used.

Upvotes: 4

PengOne
PengOne

Reputation: 48398

Since you have retain in

@property (nonatomic, retain) someClass *aProperty;

any instance of AClass will automatically retain its property aProperty. Therefore you will need to call [aProperty release] in the dealloc method of AClass.

Every time you call aMethod, you are creating a new instance of someClass without release the previous instance. This will result in a huge leak. You can fix this in one of two ways. Either release the previous aProperty value or add in a call to autorelease.

Upvotes: 2

Related Questions