Objective C: Mutable Array gets refreshed after a new viewController is pushed onto the navigationController
What I am doing: I am implementing a navigation controller with 2 view Controllers, a root Controller (displayed at launch) and a table View Controller. I am creating a NSMutableArray in the table View Controller to store a list of contacts selected from the address book.
Issue: When I click back to the root view controller from the table view controller, my NSMutable Array gets refreshed, so when I click to display my table view again, nothing is displayed. What is the best way to prevent开发者_Go百科 this from happening? I instantiated my NSMutable Array as such in my table view controller
if (!personArray)
{
self.personArray = [[NSMutableArray alloc] init];
}
Any advise is greatly appreciated!
Thanks
Zhen
One way to do it is to make the person array a property of your root view controller or your app delegate, so that it's created (possibly read from a file) when the app launches and continues to live until the app terminates.
Another way is to leave it as is, but prevent your table view controller from being deallocated when the user goes back to the root view controller. Your root view controller code probably looks something like:
-(IBAction)showMeTheTable:(id)sender
{
MyTableViewController *mtvc = [[MyTableViewController alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:mtvc animated:YES];
[mtvc release];
}
You can change that so that the table view controller is created early in the root view controller's lifetime and retained, and then always push the same table view controller rather than creating a new one every time:
-(IBAction)showMeTheTable:(id)sender
{
[self.navigationController pushViewController:self.tableViewController animated:YES];
}
Your tableview is going to be deallocated when going back and then recreated when going forward again. Therefore it is not possible to keep it around in the tableview. Instead, you should create a new class that will not be destroyed during this process. Possibly you can store the array in your application delegate, but it would probably be better to create a new class specifically meant for cacheing data.
精彩评论