user3926776
user3926776

Reputation:

remember selected cells in tableView

I'm trying to create to store the selected cells in array and then when u then press on the backbutton and go back to this viewcontroller it should remember the selected cells. The indexPaths is saved correctly in the singleton classes, but it does not seem like the [pickedArray containsObject:indexPath] is being triggered? what am i doing wrong?

could it be because the NSIndexPath number is not equal? if yes how can i fix this?

rentType.h NSObject

@interface rentType : NSObject


@property BOOL picked;

@end

viewDidLoad

 menuArray = [NSArray arrayWithObjects:@"Under 12 måneder", @"Over 12 måneder", @"Ubegrænset", nil];

tableView Methods

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.textColor = [UIColor colorWithRed: 0.137 green: 0.145 blue: 0.157 alpha: 1];
    cell.textLabel.font = [UIFont fontWithName: @"HelveticaNeue" size: 14];



    obj = [menuArray objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",obj];

    if (obj.picked) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }


    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (obj.picked) {
        obj.picked = NO;
    } else {
        obj.picked = YES;
    }
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationFade];
}

Upvotes: 0

Views: 629

Answers (2)

Arnav
Arnav

Reputation: 688

You can do this by just one line of code:

 tableView.indexPathsForSelectedRows

Upvotes: 1

Phillip Mills
Phillip Mills

Reputation: 31026

I believe it would be a better approach to have a picked property inside each of the objects that you're storing in menuArray. That way, each object could tell you whether it was picked without having to juggle a second array that has a chance of becoming out-of-phase with the one that's being used for the cell content.

The idea is to set up your objects that match the cells so that they are not strings, but custom objects. Then you can get rid of pickedArray and write:

   CustomObject *obj = [menuArray objectAtIndex:indexPath.row];
   cell.textLabel.text = obj.text;

    if (obj.picked) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

Upvotes: 1

Related Questions