iPhone - simplest way to hold a tableview's state?
I currently have a simple tableview with 7 cells in it. When a row is selected I add a checkmark to a cell and vice-versa when a cell that is already checked is selected it is unchecked.
However when I go back out of the tableview and return all the check mark开发者_StackOverflow中文版s are gone.
I was wondering what is the simplest solution in IOS to keep the state of the checked cells so that when I return to the table view the check marks are still there for the checked cells?
I read a number of posts a while back on the subject. It figures I can't find the exact one that helped me, but here are a few I thought were good:
- Jeff LaMarche has a post on this
- Matt Gallagher - Cocoa With Love did a post too
- Tutorial on 'checkbox lists' is closer to something I personally used
The simplest way to do this would be to save these checked states somewhere in the table view. That assumes that your table view is staying in memory somewhere when you leave the screen. If the table view is not being saved in memory (as in you are allocating it when you decide to navigate there, and is being released when you leave), then it would probably be easiest to save it somewhere in the app delegate, since we know that is remaining in memory for the duration of the application's lifespan
What you want to do is on your data model which supplies the data each cell is set up from, add a flag (if you do not already have one) which will be used to indicate this case. Ensure you set up the checkmark on the cell in tableView:cellForRowAtIndexPath:
based on your data model for that particular cell.
When you come back to it, provided your data source hasn't changed, when the tableview sets up its cells again before displaying the tableview, it'll use that data to show the checkmark based on the setting in your data source.
store tableview state in sqlite
save the state in NSUserDefaults.
in your didSelectRowAtIndexPath tableView delegate method set the user default with something like this:
NSUInteger defaultsCheckedRow=[[NSUserDefaults standardUserDefaults] integerForKey:@"rowForCheckedCellInNameOfTableViewController"];
if (defaultsCheckedRow==indexPath.row){
// deselect the row
defaultsCheckedRow=defaultsCheckedRow*-1;
}else{
defaultsCheckedRow=indexPath.row;
}
[[NSUserDefaults standardUserDefaults] setInteger: defaultsCheckedRow forKey: "rowForCheckedCellInNameOfTableViewController"]
[[NSUserDefaults standardUserDefaults] synchronize];
[self.tableView reloadData];
Then in your cellForRowAtIndexPath: Data source delegate method you can do something along the lines of:
NSUInteger defaultsCheckedRow=[[NSUserDefaults standardUserDefaults] integerForKey:@"rowForCheckedCellInNameOfTableViewController"];
if (indexPath.row==defaultsCheckedRow){
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType=UITableViewCellAccessoryNone;
}
精彩评论