我试图为我的UITableView保存选定的行。因此,当用户返回到屏幕时,它会显示他们的最后选择。
这是我试过的代码,我认为这样可以解决问题:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.lastIndexPathUsed = indexPath;
NSData *responseData = [NSKeyedArchiver archivedDataWithRootObject:indexPath];
[[NSUserDefaults standardUserDefaults] setObject:responseData forKey:@"IndexPathData"];
[[NSUserDefaults standardUserDefaults] synchronize];
[tableView reloadData];
}
然后在我的viewDidLoad
中- (void)viewDidLoad
{
[super viewDidLoad];
NSData *responseData = [[NSUserDefaults standardUserDefaults]objectForKey:@"IndexPathData"];
NSIndexPath *index = [NSKeyedUnarchiver unarchiveObjectWithData:responseData];
self.lastIndexPath = index;
}
但是,responseData
还没有保存索引路径。它总是NULL。甚至在didSelectRowAtIndexPath方法中。
有人知道更好的方法吗?
答案 0 :(得分:1)
您可以将其另存为两个值并稍后重新创建NSIndexPath:
单独保存indexPath.row和indexPath.section,然后使用:
重新创建它[NSIndexPath indexPathForRow:inSection:]
答案 1 :(得分:1)
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
[userdefaults setObject:[NSString stringWithFormat:@"%d",indexPath.row] forKey:@"lastIndexPathUsed"];
}
然后在viewDidLoad方法
中 -(void)viewDidLoad
{
[super viewDidLoad];
self.lastIndexPath = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastIndexPathUsed"];
}