使用iOS6中的restorationIdentifier保存UIImageView的状态

使用iOS6中的restorationIdentifier保存UIImageView的状态,ios,objective-c,ios6,state-restoration,Ios,Objective C,Ios6,State Restoration,我在文档中读到,@属性(非原子,复制)NSString*restorationIdentifier能够保存UIImageView属性的状态,如位置、角度等。我尝试添加这些方法 -(BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder { return YES; } -(BOOL)application:(UIApplication *)applicatio

我在文档中读到,
@属性(非原子,复制)NSString*restorationIdentifier
能够保存
UIImageView
属性的状态,如位置、角度等。我尝试添加这些方法

-(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;
}
关于国家保护的有用文章:

您可以使用[super DecodeRestorableStateWith Coder:]进行编码,反之亦然。一种让人们保持警觉的方法。