2016-03-19 51 views
0

专家,保存经过地位的UITableViewXamarin.iOS - NSUserDefaults的使用

请参见下面的,因为我有一个表,要保存在NSUserDefaults的Xamarin.iOS内的表的检查状态。你将如何去保存检查状态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(); 
    } 

} 
} 
+1

问题是? – jbm

+0

你说明你想做什么,并且发布了一些代码,但是问题是什么?什么是实际问题?请参阅[问]和[mcve] –

+0

对不起,我编辑了我的回复以上陈述这个问题。 – pkozlowski

回答

1

存储/读取一个boolean 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文件?

+0

非常感谢!我确实采取了通过JSON文件跟踪选择的方法。完美的作品。 – pkozlowski

+0

@pkozlowski不客气。 :) –