如何保存窗口状态

      在iPhone手机客户端开发过程中经常会涉及到一些问题,如:如何保存窗口状态等等。

      当应用别切到后台后,很难保证应用不被杀掉(用户主动杀掉或被系统杀掉),如果被杀掉,当程序

再次启动时就需要恢复前一次状态。ios sdk 6.0提供了一些接口让我们很容易实现对应用状态的保存,具体做法如下:

      首先在AppDelegate中要实现如下几个方法: 

- (BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder {
    return YES;
}

- (BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder {
    return YES;
}

- (void)application:(UIApplication *)application willEncodeRestorableStateWithCoder:(NSCoder *)coder {
    [coder encodeObject:self.window.rootViewController forKey:PDAppDelegateRootViewCTLKey];
}

- (void)application:(UIApplication *)application didDecodeRestorableStateWithCoder:(NSCoder *)coder {
    UIViewController * ctl = [coder decodeObjectForKey:PDAppDelegateRootViewCTLKey];
    if (ctl) {
        UIWindow * window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        window.rootViewController = ctl; 
        
        self.window = window;
    }
}

 程序启动时会先调用shouldRestoreApplicationState方法,因为方法返回YES,表明恢复应用状态,这时会顺序调用didDecodeRestorableStateWithCoder方法,最后调用didFinishLaunchingWithOptions, 该方法实现如下:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if (_window == nil) {
        self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
        // Override point for customization after application launch.
        PDViewController *viewController = [[[PDViewController alloc] initWithNibName:nil bundle:nil] autorelease];
        self.window.rootViewController = viewController;
    }

    [self.window makeKeyAndVisible];
    return YES;
}

 这里还涉及到一个ViewController的写法,该程序主要是为了保存ViewCtronller中的状态,所以ViewCtronller必须要支持状态恢复,如下:

@interface PDViewController : UIViewController<UIViewControllerRestoration> {
    int _sliderValue;
}

@end

 为了支持状态恢复必须实现UIViewControllerRestoration接口,同时还有几个方法需要实现:

- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
    [super encodeRestorableStateWithCoder:coder];
    [coder encodeInt:_sliderValue forKey:@"sliderValue"];
}

- (void)decodeRestorableStateWithCoder:(NSCoder *)coder {
    [super decodeRestorableStateWithCoder:coder];
    _sliderValue = [coder decodeIntForKey:@"sliderValue"];
    
    UISlider *slider = (UISlider*)[self.view viewWithTag:SliderTag];
    slider.value = _sliderValue;
    
    UITextField *textField = (UITextField*)[self.view viewWithTag:TextFieldTag];
    textField.text = [NSString stringWithFormat:@"%d", _sliderValue]; 
}

+ (UIViewController *) viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder {
 
    UIViewController *retViewController = [[[PDViewController alloc] initWithNibName:nil bundle:nil] autorelease];
  
    return retViewController;
}

 通过以上基本既可实现窗口状态的保存 

猜你喜欢

转载自enfeng-yang.iteye.com/blog/1829401