简体   繁体   中英

Memory management issue with 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 ie would the retain count be 2?

from the interface:

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];

不知道,但我知道如何找出答案,如果您通过XCode Profiler运行并选择“分配”,它将列出每个对象的计数。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM