【问题标题】:Save the state of UIImageView using restorationIdentifier in iOS6iOS6中使用restoreIdentifier保存UIImageView的状态
【发布时间】:2013-04-08 06:36:25
【问题描述】:

我在文档中读到@property(nonatomic, copy) 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 没有得到保留。这里有什么问题?

【问题讨论】:

    标签: ios objective-c ios6 state-restoration


    【解决方案1】:

    为了使状态保存和恢复工作,始终需要两个步骤:

    • 应用代理必须选择加入
    • 每个视图控制器或视图要 保存/恢复必须分配一个恢复标识符。

    您还应该为需要保存和恢复状态的视图和视图控制器实现 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

    【讨论】:

    • 你有 [super decodeRestorableStateWithCoder:] 用于编码,反之亦然。一种让人们保持警觉的方法。
    猜你喜欢
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    相关资源
    最近更新 更多