Search code examples
iosuitableviewxcode4.6uiswitchaccessoryview

UISwitch in each sectioned table row's accessoryView


I am new to iOS coding, I looked around here in SO and tried several approaches to solve this, but nothing seems to work. I'm shure it's because of some silly mistake of mine :-)

I have a sectioned table, with about 25 rows in total, divided in 2 sections. There is a switch for each cell.accessoryView, i try to store the switch state, when it changes, in a NSArray, but logging the array content at that index weirdly returns 0 in any case. (The array is instantiated as a property (nonatomic, readwrite) of the TableViewController, and synthesized)

And obviously , when i scroll the table up and down, all the switches return in the default OFF state.

Thanks for any help!

- (void)viewDidLoad
{
[super viewDidLoad];
//countries dict and switch state array init..  
self.countries = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"countries" ofType:@"plist"]];
NSNumber *b = [NSNumber numberWithBool:NO];
for (int i=0; i<210; i++) {
    [statiSwitch addObject:b];
    NSLog(@"%d", [[statiSwitch objectAtIndex:i] integerValue]);
}

//tableview drawing..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellWithSwitch";    
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

NSString *continent = [self tableView:tableView titleForHeaderInSection:indexPath.section];
NSString *country = [[self.countries valueForKey:continent] objectAtIndex:indexPath.row];

//Simple tag calculation...
NSInteger tagOb = indexPath.section * 100 + indexPath.row;

UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
[mySwitch addTarget:self action:@selector(switchChange:) forControlEvents:UIControlEventValueChanged];
mySwitch.tag = tagOb;
if ([statiSwitch count] > tagOb) {
    [mySwitch setOn:[[statiSwitch objectAtIndex:tagOb] boolValue] animated:NO];
     }

cell.textLabel.text = country;    
cell.accessoryView = mySwitch;

return cell;
}

And then the method called at switch status change:

- (void) switchChange:(UISwitch *)sender {
NSNumber *c = [NSNumber numberWithBool:sender.on];
[statiSwitch replaceObjectAtIndex:sender.tag withObject:c];

NSLog(@"switch tag is: %i and state is: %d", sender.tag, sender.on);
NSLog(@"switch states array value: %d", [[statiSwitch objectAtIndex:sender.tag] integerValue]);
}

Solution

  • I think you had omitted to initialize statiSwitch before adding objects to it.

    In viewDidLoad before the for-loop, add this line

    statiSwitch = [NSMutableArray array];