Can't understand how to save and load checked / unchecked tableview cells. For now, my code works for only checked cells, but when I take off the checkmark – all objects have removed from array, but I want to remove only unchecked object.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    bool isSelected = (cell.accessoryType == UITableViewCellAccessoryCheckmark);
    cell.accessoryType = isSelected ? UITableViewCellAccessoryNone : UITableViewCellAccessoryCheckmark;

    //loading my whole plist to overwrite it then
    NSString *path = [DOCUMENTS stringByAppendingPathComponent:@"userData.plist"];
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:path];

    //loading fragment of plist with personal qualities which I want to check / uncheck in my tableview
    NSMutableArray *oldData = data[@"myObjects"];

    //new array to overwrite the old
    NSMutableArray *newData=[[NSMutableArray alloc] init];

    if (isSelected) {
        [newData removeObject:cell.textLabel.text]; //don't know  where I should paste the code for removing object, this line no matter doesn't works
    } else {
        [newData addObjectsFromArray:oldData];
        [newData addObject:cell.textLabel.text];
    }

    [data setObject:newData forKey:@"myObjects"];
    NSData *dataToPlist = [NSPropertyListSerialization dataWithPropertyList:data
                                                                     format:NSPropertyListXMLFormat_v1_0
                                                                    options:0
                                                                      error:nil];
    [dataToPlist writeToFile:path atomically:YES];
}

My plist My tableview

有帮助吗?

解决方案

Try this:

 //new array to overwrite the old
NSMutableArray *newData=[[NSMutableArray alloc] initWithArray:oldData];

if (isSelected) {
    [newData removeObject:cell.textLabel.text]; //don't know  where I should paste the code for removing object, this line no matter doesn't works
} else {
    [newData addObject:cell.textLabel.text];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top