I’m using iOS 4 and I have some memory management problems that I don’t understand. I will try to simplify the code:
- (void)viewDidLoad
{
NSMutableArray *buttonArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [othercollection count]; i++)
{
// Push objects to button array
}
self.buttonSliderView = [[ButtonSliderView alloc] initWithButtons:
buttonArray];
[buttonArray release];
[self.view addSubview:self.buttonSliderView];
[buttonSliderView release];
}
- (void) viewDidAppear
{
if ([buttonSliderView.menuButtons count] > 0)
{
// ...
}
}
In ButtonSliderView.m:
- (id)initWithButtons:(NSMutableArray *)buttonArray
{
self = [super init];
if (self)
{
menuButtons = buttonArray;
}
}
I have an error in the first line of viewDidAppear. menuButtons were released. How can I fix this? Which is the correct solution?
If I change button array declaration to this:
NSMutableArray* buttonArray = [[[NSMutableArray alloc] init] autorelease];
…and remove the release sentence, it crashes too. If I remove the release sentence and don’t autorelease, it works, but there are memory leaks.
The problem is that you omit the setter and assign menuButtons property directly. Try this:
You didn’t show how the menuButtons property is declared, but I assume it is:
This will retain menuButtons automatically for you whenever you set it with the setter. If you have your property declared like this:
then you need to retain the array manually: