ios - 使用函数重新加载表/数组?

标签 ios objective-c iphone arrays 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];
}

我这样调用它:

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/

相关文章:

ios - 在 Swift 中获取图像名称 UIImagePickerController

iphone - 使用 NSLayoutManager 计算每个字形的帧

iphone - 将值传递给委托(delegate)方法

ios - NSDate 格式没有显示预期的内容

ios - 应用程序在启动时崩溃

ios - self.window cornerRadius - 没有状态栏

iphone - CGContextDrawImage 跨设备的字节值不一致?

iphone - 当 UIButton 状态改变时执行操作

ios - Swift 中基于图像的动画

objective-c - 访问 UITableViewCell 的 TouchBegan/Moved/Ended