有人知道为什么这个 Table View 代码会崩溃吗?
这个,在我的 viewDidLoad
中:
itemArray = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", nil];
然后,在我的 cellForRowAtIndexPath
方法中:
cell.textLabel.text = [NSString stringWithFormat:@"Item (%@)", [itemArray objectAtIndex:indexPath.row]];
当我向下滚动(即对象 1 离开屏幕)然后向后滚动以尝试查看对象 1 时,它在前一行崩溃了。
如果我用这样的东西替换有问题的行就没问题了:
cell.textLabel.text = @"test";
更新:答案是数组没有被保留。 此行解决了问题:
itemArray = [[NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", nil] retain];
或
itemArray = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", nil];
最佳答案
您的 itemArray 似乎没有被保留。 arrayWithObjects:
返回一个自动释放的对象。您需要保留
或复制
它,或者使用保留属性的语法糖。
关于objective-c - UITableView 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6418255/