Elad Shevah
Elad Shevah

Reputation: 37

TableView with multiple switches

I have a tableView with multiple of switches(one switch for each row). what is the best way to save the state for the switches? and in what methods should I save and retrieve the data?

Upvotes: 0

Views: 283

Answers (3)

jbat100
jbat100

Reputation: 16827

If you want it to be persistent through app launches you could save an NSDictionary of NSNumbers (numberWithBool:), or save them in NSUserDefaults (setBool:forKey:) if the table view always shows the same choice.

Upvotes: 0

jrturton
jrturton

Reputation: 119242

Save the data in an array, you haven't given any context but you may be using an array of some sort already to drive the number of rows in the table and the rest of the content?

You set the value of the switch in the cellForRowAtIndexPath: method. I've assumed the following:

  • You already have a pointer to the switch within the cellForRowAtIndexPath method
  • You have already created the mutable array and filled it with NSNumber objects

So, when you've got your cell and are about to return it:

cellSwitch.on = [[switchValueArray objectAtIndex:indexPath.row] boolValue];

Your setter method is a little more complicated because all of your switches will be calling the same action method. Therefore you need to find out which row the switch was in. This would be in the method you've connected to Value Changed of the switch

-(IBAction)switchValueChanged:(UISwitch*)sender
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell*)[sender superview]];
    [switchValueArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:sender.on]];
}

Upvotes: 1

mafis
mafis

Reputation: 1165

I think one of the easiest way is to use a dictionary with the rowid as key and the value as bool.

Upvotes: 0

Related Questions