重新装载表/数组与功能?
问题描述:
我有这段代码,我做错了什么?重新装载表/数组与功能?
我有一个函数,我称之为将一些字符串放入数组中。然后在某些时候我想在用户编辑字符串之后重新加载它。这是函数:
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];
}
啊我想这可能是事做与此,但没有锁住(典型的我!)谢谢!!!!! – 2010-09-20 14:22:42
虽然有一个小问题,是否有一个原因,我必须说self.monArrayA而不是monArrayA? – 2010-09-20 14:26:18
self.monArrayA相当于调用[self setMonArrayA]方法(如果使用@synthesize,则自动生成),并且monArrayA被保留在其中。你可以写monArrayA = [lessonFunc()retain],但是你需要手动释放以前的monArrayA值。使用属性使生活变得更容易 – Vladimir 2010-09-20 14:46:12