开发者

Objective C: Query about releasing instance property

I hav开发者_C百科e 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'?


  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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜