I have a table view with a custom cell (UISwitch on every cell of the tableview).
I have set my cell like this:
switchView = [[UISwitch alloc] initWithFrame:CGRectMake(200.0f, 5.0f, 75.0f, 30.0f)];
cell.accessoryView = switchView;
[switchView setOn:NO animated:NO];
[switchView addTarget:self action:@selector(favorite:) forControlEvents:UIControlEventValueChanged];
[cell addSubview:switchView];
And the action that is called by the user when he changes the UISwitch is:
-(IBAction)favorite:(id)sender
{
indexPath = [self.tableView indexPathForCell:(UITableViewCell*)[sender superview]];
NSMutableArray *favoriteList = [[NSMutableArray alloc]init];
NSString *favoriteItem = [self.tableView cellForRowAtIndexPath:indexPath].textLabel.text;
NSLog(favoriteItem);
if ([switchView isOn])
{
[favoriteList addObject:favoriteItem];
NSUserDefaults *favoriteDefaults = [NSUserDefaults standardUserDefaults];
[favoriteDefaults setObject:favoriteList forKey:@"MyFavorites"];
NSLog(@"%@", favoriteList);
}
else
{
[favoriteList removeObject:favoriteItem];
NSUserDefaults *favoriteDefaults = [NSUserDefaults standardUserDefaults];
[favoriteDefaults setObject:favoriteList forKey:@"MyFavorites"];
NSLog(@"%@", favoriteList);
}
}
The problem is:
When testing the app, just the last item (cell) of the table view works properly.
For the others, the debugger returns that the state of the UISwitch is always “OFF”.
What is the problem?
A couple of immediate reactions:
In
(IBAction)favorite:(id)senderyou are not grabbing the switchView for the cell in question, but rather just using what was used by the last reference of that class ivar. Likewise, in yourcellForRowAtIndexPath, you appear to be setting (and repeatedly resetting) this same, singleswitchViewivar. Probably shouldn’t be an ivar at all. You could makeswitchViewa local variable ofcellForRowAtIndexPath. You could also make it a local variable offavorite. But most importantly,favoriteshould setting it asUISwitch *switchView = sender.I presume you want to save all of your favorites to user defaults. Your current
(IBAction)favorite:(id)senderwill recreate favoriteList each time, and it will have either one item in it or no items in it, but certainly discarding any other favorites you may have selected in the past.A minor point, but if you set the accessory cell, you don’t need to also add the switchView to the subview.
So, I’d suggest modifying
cellForRowAtIndexPathas follows:This uses
isFavorite:Then, obviously, you need to define your
toggleFavoriteSwitch(previously calledfavorite) method:And this is updating user defaults as follows:
Hopefully this remedies your issue.