NSMutableArray is not like C array. It's more like a list. So
BOOL checked = [[checkedArr objectAtIndex:indexPath.row] boolValue];
[checkedArr removeObjectAtIndex:indexPath.row];
will not work like you want.
- Also
[cheval insertObject:(checked) ? @"FALSE":@"TRUE" atIndex:indexPath.row];
will crash if cheval
contains less objects than indexPath.row
.
I would suggest using NSMutableDictionary
instead of NSMutableArray
. You may use an NSIndexPath
object as a key. And change a little bit algorithm:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *indexPathKey = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]; // we use this code because in iOS 7 indexPath has type UIMutableIndexPath
BOOL checked = ![checkedDict[indexPathKey] boolValue];
checkedDict[indexPathKey] = @(checked);
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *newImage = (checked) ? [UIImage imageNamed:@"tick.png"] : [UIImage imageNamed:@"white_bg.png"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
cell.accessoryView=button;
}
Also why don't you use default checkmark. If you use it you should change your code in the following way:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *indexPathKey = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]; // we use this code because in iOS 7 indexPath has type UIMutableIndexPath
BOOL checked = ![checkedDict[indexPathKey] boolValue];
checkedDict[indexPathKey] = @(checked);
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = checked ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
}