【问题标题】:Loading Cells' Accessory State from NSUserDefaults从 NSUserDefaults 加载单元格的附件状态
【发布时间】:2014-12-21 16:27:11
【问题描述】:

这就是我当前保存单元格复选标记状态的方式(有效):

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  {\

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

NSUserDefaults  *defaults = [NSUserDefaults standardUserDefaults];
if (cell.accessoryType == UITableViewCellAccessoryNone) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    [defaults setBool:YES forKey:cell.textLabel.text];

} else {
    cell.accessoryType = UITableViewCellAccessoryNone;
    [defaults setBool:NO forKey:cell.textLabel.text];
}
[defaults synchronize];

}

这就是我尝试检索它们的方式:

-(void)viewWillAppear:(BOOL)animated {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

for (int section = 0; section < [self.tableView numberOfSections]; section++) {
    for (int row = 0; row < [self.tableView numberOfRowsInSection:section]; row++) {
        NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
        UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:cellPath];
        if (![defaults valueForKey:cell.textLabel.text]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
}
}

NSUser 默认保存正确(我知道这是因为 NSLog),但是当我退出并返回表格视图时,没有单元格有复选标记。

如果我换行:

if (![defaults valueForKey:cell.textLabel.text]) {

到

if ([defaults valueForKey:cell.textLabel.text]) {

表格视图重新出现,所有单元格都带有复选标记。

谢谢

【问题讨论】:

    标签: ios xcode uitableview cell


    【解决方案1】:

    您的问题是[self.tableView cellForRowAtIndexPath:cellPath]; 可以返回 nil 如果当前没有表中该行的单元格 - 这几乎可以肯定是 viewDidLoad 的情况,因为视图尚不可见。即使表格已加载,如果单元格已滚动到视图之外并且单元格对象已被释放或重用,该方法仍然可以返回 nil。

    最好将选择状态存储在 NSMutableDictionary 中,并将字典存储在 NSUserDefaults 中。然后您可以检查cellForRowAtIndexPath中的字典内容并相应地设置附件。

    【讨论】:

    • 啊,好吧,我想我明白了。谢谢,我会尽快尝试
    猜你喜欢
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多