开发者

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 autoreleased 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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜