how to save and restore state Using storyboard in iOS?

378 views Asked by At

I am working on chat application. I want to store the application state of all view controller.

My code to store app state:

+ (UIViewController *)viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder
 {
 MoreController *vc = nil;
 UIStoryboard *storyboard = [coder decodeObjectForKey:UIStateRestorationViewControllerStoryboardKey];
 if (storyboard)
 {
      vc = (MoreController *)[storyboard instantiateViewControllerWithIdentifier:@"MoreController"];
      vc.restorationIdentifier = [identifierComponents lastObject];
      vc.restorationClass = [MoreController class];
 }
 return vc;
}

 - (void)encodeRestorableStateWithCoder:(NSCoder *)coder
 {
       [coder encodeObject:self.view forKey:@"save"];
       [coder encodeObject:_btnoiwii forKey:@"save"];

      [coder encodeObject:_tblMore forKey:kUnsavedEditStateKey];
           [super encodeRestorableStateWithCoder:coder];
 }

 - (void)decodeRestorableStateWithCoder:(NSCoder *)coder
  {
   self.view = [coder decodeObjectForKey:@"save"];
  _btnoiwii= [coder decodeObjectForKey:@"save"];

  _tblMore = [coder decodeObjectForKey:kUnsavedEditStateKey];
  [super decodeRestorableStateWithCoder:coder];

  }

I am able to encode the state of application but not decode. In app delegate class I added shouldRestoreApplicationState,willEncodeRestorableStateWithCoder

Please give me appropriate solution to save and restore state of application in iOS.

1

There are 1 answers

0
badhanganesh On

You should not save the whole table view and view controller's super view like that. When UIKit restores your view controller, it automatically restores all the views for you. Make sure you save your data source and when decoding, reload your table view.

If you want to restore indexes of your tableView, you need to conform to this protocol, UIDataSourceModelAssociation and implement these methods: indexPathForElementWithModelIdentifier, modelIdentifierForElementAtIndexPath

Also make sure that you are recovering the navigation stack where your view controllers are pushed.