我有这段代码,我做错了什么?
我有一个函数,我称之为将多个字符串播放到数组中。然后在某个时候我想在用户编辑字符串后重新加载它。这是函数:
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];
}
当我按下该按钮时,它几乎总是崩溃。非常感谢任何帮助,谢谢!
最佳答案
可能的问题是,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];
}
关于ios - 使用函数重新加载表/数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3752234/