gpt4 book ai didi

ios - 为什么在交互和滚动时 UITableView 会发生内存泄漏?

转载 作者:行者123 更新时间:2023-11-28 21:29:46 26 4
gpt4 key购买 nike

我的 tableview 工作正常,加载所有数据都没有问题。我在使用 didSelectRowAtIndexPath 并添加/删除单元格上的复选框时遇到问题。我将选中前 10 个单元格,向下滚动并在我未点按的单元格上看到一个复选框。

是什么导致了这个问题?下面是我的表格 View 代码。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = @"reuseCellForFilter";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
Category *category = [self.categories objectAtIndex:indexPath.row];
cell.textLabel.text = category.title;

return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.categories.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{


NSLog(@"%@", indexPath);
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
Category *category = [self.categories objectAtIndex:indexPath.row];
if(cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[self.titles addObject:category];
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
for (Category *categoryID in [self.titles reverseObjectEnumerator]) {
if (categoryID.categoryID == category.categoryID) {
[self.titles removeObject:categoryID];
}
}
}
}

最佳答案

您需要在 didSelectRowAtIndexPath 方法中保存选中/未选中状态,然后在 cellForRowAtIndexPath 方法中恢复它。

例如:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = @"reuseCellForFilter";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
cell.selectionStyle = [self.selected containsObject:category.categoryID] ? UITableViewCellSelectionStyleCheckmark : UITableViewCellSelectionStyleNone;
Category *category = [self.categories objectAtIndex:indexPath.row];
cell.textLabel.text = category.title;
return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Category *category = [self.categories objectAtIndex:indexPath.row];
if ([self.selected containsObject:category.categoryID]) {
[self.selected removeObject:category.categoryID];
self.tableView reloadRowsAtIndexPaths:@[indexPath] withAnimation: UITableViewRowAnimationNone];
}
}

didSelectRowAtIndexPath 方法也有问题。将类别标记为选中您将此类别添加到数组中。要取消选中类别,请从数组中删除 categoryID

[self.titles addObject:category];
...
[self.titles removeObject:categoryID];

关于ios - 为什么在交互和滚动时 UITableView 会发生内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36650124/

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