我在文档中读到@property(nonatomic, copy) NSString *restorationIdentifier
能够保留UIImageView
属性的状态,例如位置,角度等。我尝试添加方法
-(BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder
{
return YES;
}
-(BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder
{
return YES;
}
到视图控制器。我已将视图控制器的恢复ID设置为IB中的@"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没有得到保留。这有什么不对?
答案 0 :(得分: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