I am showing comments in UItableView and created delete button in Cell..When I delete any comment It will delete. and I used [Tableview reloadData], but It always delete last cell from table and when I checked the deleted comment next time it is fine.. Why table view always delete last cell.. My code is
- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%i",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
//delete button in uitableview cell ================================
deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
deleteBtn.frame = CGRectMake(270, 10, 20, 20);
//[deleteBtn setTitle:@"delete" forState:UIControlStateNormal];
[deleteBtn setImage:[UIImage imageNamed:@"deletefb.png"] forState:UIControlStateNormal];
deleteBtn.tag = indexPath.row;
[deleteBtn addTarget:self action:@selector(delete:) forControlEvents:UIControlEventTouchUpInside];
deleteBtn.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
[cell.contentView addSubview:deleteBtn];
}
return cell;
}
Delete method is
- (void )delete:(id)sender {
UIButton *myDeleteButton = (UIButton *)sender ;
//delete method of comment
NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:1];
[variables setObject:@"delete" forKey:@"method"];
[fbGraph doGraphPost:[NSString stringWithFormat:@"%@",[(Facebook *)[tableArray objectAtIndex:myDeleteButton.tag]postId]] withPostVars:variables];
//load tableview
[self responseMethod]; //method to load comments
//show alert
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Deleted"
message:@"" delegate:nil
cancelButtonTitle:@"Ok" otherButtonTitles:nil ];
[alert show];
[alert release];
}
Try moving
deleteBtn.tag = indexPath.row;outside of theif (cell == nil)condition.In your current setup, when you reuse a cell rather then instantiate a new one the
tagwill reference the oldindexPath.rowrather than that of the new one. This may well be why you’re seeing cells deleted other than the one expected.Also, you don’t seem to grasp the concept of reusing table cells. The identifier should be a constant string applied to all cells, not a dynamic one as you have setup here. For instance