Memory leak coming from this code, how do i get rid of it?
This is my code, which the app runs upon changing to the view that it's inside of. It's causing a memory leak with colourButtonsArray when you change to this view more than once (so not the first time you run it) but i'm unsure how to get rid of it:
-(void)setColours {
colourButtonsArray = [[NSMutableArray alloc] init];
[colourButtonsArray addObject:@""];
int buttonsI = 1;
while (buttonsI < 7)
{
//Make a button
UIButton *colourButton = [UIButton buttonWithType:UIButtonTypeCustom];
c开发者_Python百科olourButton.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++;
}
}
Where do you release colourButtonsArray
?
If you call setColours
more than once you'll be creating a new array for colorButtonsArray
and leaking the old one each time (assuming you only release colourButtonsArray
in your dealloc method, or if you don't release it at all).
use accessors properly, and lock as necessary. this may help:
-(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 */
}
精彩评论