保存在iOS6的

问题描述:

使用restorationIdentifier所述的UIImageView的状态I,该@property(nonatomic, copy) NSString *restorationIdentifier是能够保存一个UIImageView性能如位置,角度等的状态的我尝试添加方法保存在iOS6的

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

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

的文档中读到视图控制器。我已经在IB中将视图控制器的恢复ID设置为@"myFirstViewController

我也在视图控制器中添加了以下方法。

-(void)encodeRestorableStateWithCoder:(NSCoder *)coder 
{ 
[coder encodeObject:_myImageView.image forKey:@"UnsavedImage"]; 
[super decodeRestorableStateWithCoder:coder]; 
} 

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder 
{ 
_myImageView.image = [coder decodeObjectForKey:@"UnsavedImage"]; 
[super encodeRestorableStateWithCoder:coder]; 
} 

我应该添加在appDelegate或视图控制器前两种方法? UIImageView没有被保存。这里有什么问题?

使状态保存和恢复工作有一些总是需要两个步骤:

  • 应用程序的委托必须进行选择
  • 每个视图控制器或视图是 保存/恢复必须有分配的恢复标识符。

对于需要保存和恢复状态的视图和视图控制器,您还应该实现encodeRestorableStateWithCoder:decodeRestorableStateWithCoder:

将以下方法添加到您的UIImageView的视图控制器中。

-(void)encodeRestorableStateWithCoder:(NSCoder *)coder 
{ 
    [coder encodeObject:UIImagePNGRepresentation(_imageView.image) 
       forKey:@"YourImageKey"]; 

    [super decodeRestorableStateWithCoder:coder]; 
} 

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder 
{ 
    _imageView.image = [UIImage imageWithData:[coder decodeObjectForKey:@"YourImageKey"]]; 

    [super encodeRestorableStateWithCoder:coder]; 
} 

状态保存和恢复是一项可选功能,所以你需要通过实现两种方法使应用程序委托选入:

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

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

约状态保存有用的文章: http://useyourloaf.com/blog/2013/05/21/state-preservation-and-restoration.html

+0

你有[super decodeRestorableStateWithCoder:]进行编码,反之亦然。让人们脚踏实地的一种方法。 – 2014-12-10 20:35:38