2016-04-15 38 views
0

我的tableview工作正常,加载所有数据没有问题。当我使用didSelectRowAtIndexPath并添加/删除单元格上的复选框时,我遇到了问题。我会在前10位检查一个单元格,向下滚动并查看我没有点击的单元格上的复选框。为什么在交互和滚动时我在UITableView中有内存泄漏?

是什么导致了这个问题?以下是我的tableview代码。

-(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]; 
     } 
    } 
} 
} 
+0

确定if(categoryID.categoryID == category.categoryID)对指针类型的变量是否正确? – heximal

回答

2

您需要保存选中/取消选中状态在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];