[英]NSUserDefaults will not save selections for multiple rows
I have a button that toggles from selected to unselected. 我有一个按钮,可以从选中状态切换到未选中状态。 When the user changes it to selected I want it to save the settings.
当用户将其更改为选中时,我希望它保存设置。 Upon re-entry to the tableview, all previously selected buttons should still be selected, but they aren't.
重新进入表格视图后,仍应选择所有先前选择的按钮,但是没有选择。 With my code I'm able to set one row button, but if I select multiple rows only the last one stays selected.
使用我的代码,我可以设置一个行按钮,但是如果我选择多行,则仅最后一行保持选中状态。 Here's what I've tried:
这是我尝试过的:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// code...
if([cell.nameLbl.text isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"name"]]){
[cell.likeBtn setSelected:YES];
}else{
[cell.likeBtn setSelected:NO];
}
}
And in the delegate method for my TableViewCell 在我的TableViewCell的委托方法中
-(void)tableViewCell:(TableViewCell *)cell {
//code...
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
Car *car = self.carArray[indexPath.row];
NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
[userPreferences setObject:car.name forKey:@"name"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
What's missing to store multiple selected rows? 存储多个选定行时缺少什么?
You are replacing the value associated with the @"name"
key every time. 您每次都替换与
@"name"
键关联的值。 Instead, consider using an NSArray
as the value, modifying it in the select
and deselect
delegate methods. 相反,请考虑使用
NSArray
作为值,并在select
和deselect
委托方法中对其进行修改。 Example: 例:
// select
NSMutableArray *array = [NSMutableArray arrayWithArray:[userPreferences objectForKey:@"names"]];
[array addObject:car.name];
[userPreferences setObject:array forKey:@"names"];
// deselect
NSMutableArray *array = [NSMutableArray arrayWithArray:[userPreferences objectForKey:@"names"]];
[array removeObject:car.name];
[userPreferences setObject:array forKey:@"names"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.