专家,
请参阅下面的内容,因为我有一张表,并希望在Xamarin.iOS中的NSUserDefaults中保存表格的已检查状态。您如何在NSUserDefaults中保存已检查状态(data.Selected = true)?理想情况下,我想要的是,在每个已检查的单元格之后,我想将该值保存到NSUserDefaults中。然后,如果用户终止应用程序,则将加载他们在终止应用程序之前选择的值。任何帮助将不胜感激!
我有以下TableSource类:
namespace Project
{
public class TableSource : UITableViewSource
{
public readonly static string cellIdentifier = "cellID";
readonly Model _model;
public TableSource(Model source)
{
_model = source;
}
public override nint NumberOfSections(UITableView tableView)
{
return 1;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var value = _model[indexPath.Row];
var cell = tableView.DequeueReusableCell (cellIdentifier) ?? new UITableViewCell (UITableViewCellStyle.Default, cellIdentifier) ;
cell.TextLabel.Text = value.Name;
cell.TextLabel.Font = UIFont.FromName ("Arial", 15f);
cell.Accessory = value.Selected ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None;
return cell;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return _model.Count;
}
public override void RowSelected(UITableView tableView,NSIndexPath indexPath)
{
var cell = tableView.CellAt(indexPath);
var data = _model[indexPath.Row];
if (data.Selected)
data.Selected = false;
cell.Accessory = UITableViewCellAccessory.None;
Toast.MakeText( data.Name.ToString() + " Not Checked", Toast.LENGTH_LONG).SetGravity(ToastGravity.Center).Show();
}
else
{
data.Selected = true;
cell.Accessory = UITableViewCellAccessory.Checkmark;
Toast.MakeText( data.Name.ToString() + " Checked", Toast.LENGTH_LONG).SetGravity(ToastGravity.Center).Show()
}
cell.Selected = false;
tableView.ReloadData ();
}
}
}
答案 0 :(得分:1)
向/从NSUserDefaults存储/获取布尔值非常简单:
// Store
bool value = data.Selected;
string key = string.Format("TableName{0}",indexPath.Row); // Some unique name
NSUserDefaults.StandardUserDefaults.SetBool (value, key);
// Fetch
bool checked = NSUserDefaults.StandardUserDefaults.BoolForKey (key);
然而,使用NSUserDefaults似乎有点苛刻。 为什么不考虑将用户的选择保存到App的Cache文件夹中的JSON文件?