开发者

Memory management issue with retain

开发者 https://www.devze.com 2023-01-26 13:13 出处:网络
When you have a property which you retain in the interface and you alloc somewhere in the code, do you need to release it in the code as well as release it in the dealloc method i.e. would the retain

When you have a property which you retain in the interface and you alloc somewhere in the code, do you need to release it in the code as well as release it in the dealloc method i.e. would the retain count be 2?

from the interface:

开发者_StackOverflow中文版
NSMutableData *xmlData;
@property (nonatomic, retain) NSMutableData *xmlData;

from the implementation:

@synthesize xmlData;

- (void)dealloc
{
    [xmlData release];
    [super dealloc];
}

xmlData = [[NSMutableData alloc] init]; 


You need to release it in dealloc.

If you need to retain it when setting is a matter of how you do it.

If you do it directly, you need to retain it:

xmlData = [[NSMutableData alloc] init];

If you use the setter, it is done automatically, so you need to release it (if it's not autoreleased):

NSMutableData *data = [[NSMutableData alloc] init];
self.xmlData = data;
[data release];


No idea but I know how to find out, if you run via XCode Profiler and pick Allocations it will list the count of each object.


In your example ... you only need to release the ivar in -(void)dealloc;

My practice is to only access ivars through the Accessor/Mutator (getters/setters), so when I allocate and initialize an ivar I do the following.

NSMutableData *lXMLData = [[NSMutableData alloc] init];
self.xmlData = lXMLData;
[lXMLData release];

I find it keeps everything nicely organised and balanced

I have also seen

self.xmlData = [[[NSMutableData alloc] init] autorelease];

(but I'm not a fan)

My approach ...

  • Access ivars only through Accessors/Mutators
  • Alloc/Init a local var
  • Assign local var to ivar (class variable)
  • Release local var
0

精彩评论

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