我有这个代码,我做错了什么?
我有一个函数,我称之为在数组中播放多个字符串。然后在某些时候我想在用户编辑字符串后重新加载它。这是功能:
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];
}
我称之为:
monArrayA = lessonsFunc(mon.P11S, mon.P21S, mon.P31S, mon.P41S, mon.P51S, mon.P61S);
然后我想按下按钮时重新加载/刷新它:
-(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];
}
当我按下那个按钮时,它几乎总是崩溃。任何帮助非常感谢,谢谢!
答案 0 :(得分:1)
可能的问题是lessonsFunc
返回自动释放的数组,该数组可能在当前范围之外变为无效(此处 - refreshLessons
函数之外)。只要您需要,尽量保留它以保持有效。为此,我建议为您的数组声明一个属性 - 编译器将自动生成setter和getter方法,为您处理大部分内存管理:
// 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];
}