Reputation: 17169
I have this code, what am I doing wrong?
I have a function which I call playing a number of strings into an array. Then at some point I want to reload it after the user has edited the strings. This is the function:
NSMutableArray *lessonsFunc(id a, id b, id c, id d, id e, id f){
monData *mon = [monData sharedData];
return [NSMutableArray arrayWithObjects:@"Before School",
[NSString stringWithFormat:@"%@", a],
[NSString stringWithFormat:@"%@", b],
@"Break",
[NSString stringWithFormat:@"%@", c],
[NSString stringWithFormat:@"%@", d],
@"Lunch",
[NSString stringWithFormat:@"%@", e],
[NSString stringWithFormat:@"%@", f],
@"After School", nil];
}
I call it like this:
monArrayA = lessonsFunc(mon.P11S, mon.P21S, mon.P31S, mon.P41S, mon.P51S, mon.P61S);
Then I want to reload/refresh it when I press the button:
-(IBAction)refreshLessons{
monData *mon = [monData sharedData];
//[monArrayA removeAllObjects];
//[monArrayA release];
//monArrayA = [[NSMutableArray alloc] init];
monArrayA = lessonsFunc(mon.P11S, mon.P21S, mon.P31S, mon.P41S, mon.P51S, mon.P61S);
//[monTable reloadData];
}
It crashes almost always when I press that button. Any help much appreciated, thanks!
Upvotes: 0
Views: 236
Reputation: 170829
The likely problem is that lessonsFunc
returns autoreleased array which may become invalid outside of the current scope (here - outside of refreshLessons
function). Try to retain it to keep it valid as long as you need. To do that I'd suggest to declare a property for your array - compiler will automatically generate setter and getter methods for you that will handle most of memory management for you:
// header
@property (nonatomic, retain) NSMutableArray * monArrayA;
//Implementation
@synthesize monArrayA;
...
-(IBAction)refreshLessons{
monData *mon = [monData sharedData];
self.monArrayA = lessonsFunc(mon.P11S, mon.P21S, mon.P31S, mon.P41S, mon.P51S, mon.P61S);
}
...
- (void)dealloc{
// Don't forget to release monArrayA in dealloc method
[monArrayA release];
...
[super dealloc];
}
Upvotes: 1