Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Another question about iPhone application state

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.

like image 988
Rémy Avatar asked Apr 07 '09 09:04

Rémy


1 Answers

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.

like image 117
Becca Royal-Gordon Avatar answered Sep 16 '22 20:09

Becca Royal-Gordon