简体   繁体   中英

Memory Leak in initWithFrame

i use a UIView subclass with an NSMutableArray of other Views to indicate values as bars.
I init it in my initWithFrame. The Instruments tells after a few create and remove of my UIView subclass that there is a leak on the alloc of the NSMutableArray.
Thats why i framed it with the if to avoid multiple objects. But doesn't help

- (id) initWithFrame :(CGRect)frame
{
self = [super initWithFrame:frame];
if (self.uiValueSubviews == nil){
    self.uiValueSubviews = [[NSMutableArray alloc]init];
}
return self;
}

- (void)dealloc {
[self.uiValueSubviews release];
[super dealloc];
}

Am i doing something wrong with the dealloc?
Thanks for your Help

Two problems I see with memory management involving your property.

  1. Properties should always be set to an autorelease d object or an object you will be releasing on your own.
  2. Never send release directly to a property. I prefer to release underlying variable if possible (ex. [_uiValueSubviews release]; )

Change the code to the following.

- (id) initWithFrame :(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self.uiValueSubviews == nil){
        //Set to autoreleased array
        self.uiValueSubviews = [NSMutableArray array];
    }
    return self;
}

- (void)dealloc {
    //nil the value
    self.uiValueSubviews = nil;
    [super dealloc];
}

You should do like this :

- (id) initWithFrame :(CGRect)frame
{
   if ((self = [super initWithFrame:frame]))
   {
     if (self.uiValueSubviews == nil){
         uiValueSubviews = [[NSMutableArray alloc]init];
   }
   return self;
}

- (void)dealloc 
{
   self.uiValueSubviews = nil;
   [super dealloc];
}

You uiValueSubviews is probably a retain property so when you alloc, your retainCount is +1 and self. +1 too.

An other way, avoiding autoreleased objects, would be:

// ...
if (self.uiValueSubviews == nil)
{
    NSMutableArray *uiValueSubviews_tmp = [[NSMutableArray alloc] init];
    // maybe do something with uiValueSubviews_tmp
    self.uiValueSubviews = uiValueSubviews_tmp;
    [uiValueSubviews_tmp release];
}
// ....

As far as I know, that's how Apple does it in their examples.

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