简体   繁体   中英

how to save and restore state Using storyboard in iOS?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM