I have another question about restoring application state, on the iPhone. Simple data (like the selected tab) can be stored in NSUserDefaults, but it is not enough.
I want to restore the whole state, including the Navigation Controllers (go to the sub-sub-sub View Controller).
My problem is that my application is divided in several xib files, so at the beginning, all the View Controllers are not instantiated. Is there any way to "force" the instanciation from a xib file ?
(I have no code under the hand, but I can try to write a small end if it is not clear)
Thanks a lot.
Calling [viewController view]
will make sure that a given view controller's XIB is loaded; once it is, you can use any of its other properties normally.
Here's what I tend to do:
@class Record; // some model object--I assume it has an integer record ID
@class DetailViewController;
@interface RootViewController : UIViewController {
IBOutlet DetailViewController * detailController;
}
- (void)restore;
...
@end
@implementation RootViewController
// Note: all detailController showings--even ones from within
// RootViewController--should go through this method.
- (void)showRecord:(Record*)record animated:(BOOL)animated {
[self view]; // ensures detailController is loaded
[[NSUserDefaults standardUserDefaults] setInteger:record.recordID
forKey:@"record"];
detailController.record = record;
[self.navigationController pushViewController:detailController
animated:animated];
}
- (void)restore {
int recordID = [[NSUserDefaults standardUserDefaults] integerForKey:@"record"];
if(recordID) {
Record * record = [Record recordWithID:recordID];
[rootViewController showRecord:record animated:NO];
// If DetailViewController has its own state to restore, add this here:
// [detailController restore];
}
}
...
- (void)viewDidAppear:(BOOL)animated {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"record"];
}
@end
@implementation MyAppDelegate
- (void)applicationDidFinishLaunching:(UIApplication*)application {
...
[rootViewController restore];
...
}
...
@end
Each level of the view hierarchy takes care of its own state saving, so the app controller doesn't have to know about all the possible views and which orders they could be in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With