2011-03-20 58 views
0

这是我的代码,应用程序运行时将其更改为其内部的视图。当你改变这种看法不止一次(所以不是你第一次运行它)这是造成与colourButtonsArray内存泄漏,但我不知道该如何摆脱它:内存泄漏来自这段代码,我如何摆脱它?

-(void)setColours { 

     colourButtonsArray = [[NSMutableArray alloc] init]; 
     [colourButtonsArray addObject:@""]; 


    int buttonsI = 1; 

    while (buttonsI < 7) 
    { 
     //Make a button 
     UIButton *colourButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     colourButton.frame = CGRectMake((53*(buttonsI-1))+3, 5, 49, 49); 
     colourButton.tag = buttonsI; 
     [colourButton addTarget:self action:@selector(colourButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
    [colourView addSubview:colourButton]; 


     [colourButtonsArray addObject:colourButton]; 


[colourButton release]; 
    buttonsI++; 
} 

}

+1

注意:你不应该释放'colourButton'。你可以使用'for'而不是'while'。 – benwong 2011-03-20 21:48:02

回答

0

你在哪里发布colourButtonsArray

如果你打电话超过一次,你将创建为colorButtonsArray一个新的阵列,每一次漏水旧setColours多个(假设你只在你的dealloc方法释放colourButtonsArray,或者如果你不释放它在所有) 。

+0

如果我把[colourButtonsArray release];在dealloc中,然后当我第二次加载视图时,它崩溃。 – Andrew 2011-03-20 21:32:00

+0

...泄漏不会立即导致崩溃。你确定你不是在这里混淆术语吗?泄漏是当你不释放你的对象时,它仍然卡在占用空间的内存中。如果反复泄漏内存,最终会导致崩溃(通过内存不足错误),但是不会像这样的单个阵列。听起来像其他事情正在发生。 – lxt 2011-03-20 21:35:36

0

正确使用访问器,并根据需要进行锁定。这可能有所帮助:

-(void)setColours { 
/* lock if necessary */ 
    self.colourButtonsArray = [NSMutableArray array]; 
    [self.colourButtonsArray addObject:@""]; 

    int buttonsI = 1; 

    while (buttonsI < 7) 
    { 
    /* Make a button */ 
     UIButton *colourButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     colourButton.frame = CGRectMake((53*(buttonsI-1))+3, 5, 49, 49); 
     colourButton.tag = buttonsI; 
     [colourButton addTarget:self action:@selector(colourButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
     [self.colourView addSubview:colourButton]; 

     [self.colourButtonsArray addObject:colourButton]; 

     // no release here: [colourButton release]; 
     buttonsI++; 
    } 

/* unlock if necessary */ 
} 
+0

你能解释'lock'是什么意思吗?我不明白。 – Andrew 2011-03-20 21:46:22

+0

@Andrew WIYF:'http://en.wikipedia.org/wiki/Lock_(computer_science)' – justin 2011-03-20 22:09:23