gpt4 book ai didi

ios - tableView 索引和 NSArray objectAtIndex 之间的冲突

转载 作者:行者123 更新时间:2023-11-29 04:37:10 27 4
gpt4 key购买 nike

我正在实现一个 TableView(ListeExercice 类),显示自定义单元格列表。这些单元格在另一个类(ExerciceTableCell 类)中定义。

在 ListeExercice 类中,我在 viewDidLoad 方法中创建了一个 NSArray,如下所示:

table1 = [NSArray arrayWithObjects:@"exo1", @"exo2", nil];
table2 = [NSArray arrayWithObjects:@"10:00", @"10:00", nil];

然后在同一个类中,我做所有事情都是为了显示表格中的单元格

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection(NSInteger)section
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView

我遇到的问题发生在以下方法中,基本上是显示正确单元格的代码所在的位置:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *exerciceTableIdentifier = @"ExerciceTableCell";
ExerciceTableCell *cell = (ExerciceTableCell *)[tableView dequeueReusableCellWithIdentifier:exerciceTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ExerciceTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}

//label1 is a label from the cell defined in the ExerciceTableCell class.

cell.label1.text = [tableIntituleExercice objectAtIndex:indexPath.row];

return cell;

问题是我在这两行之间发生了冲突:

cell = [nib objectAtIndex:0];

cell.Label1.text = [table1 objectAtIndex:indexPath.row];

显然两个“objectAtIndex”之间存在冲突。我没有任何警告,只是应用程序崩溃,并且有一个线程显示“线程 1:EXC_BAD_ACCESS(代码 = 1 ....)

对我能做什么有什么建议吗?

最佳答案

如果您没有使用 ARC,则这是一个简单的内存管理错误。您必须保留这些行中的两个数组:

table1 = [NSArray arrayWithObjects:@"exo1", @"exo2", nil];
table2 = [NSArray arrayWithObjects:@"10:00", @"10:00", nil];

否则,对象将在调用 tableView:cellForRowAtIndexPath: 之前被释放。对于此类错误,您通常应该始终使用属性 setter 为 ivars/properties 赋值。 setter 关心为您进行正确的内存管理。

关于ios - tableView 索引和 NSArray objectAtIndex 之间的冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10928336/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com