Question

I am adding UIImageView on a button click. I want to restore it using UIKit. I am getting restoration identifier in:

 - (void)decodeRestorableStateWithCoder:(NSCoder *)coder;

How can I decode this UIImageView?

Was it helpful?

Solution

i have used this code in one of my app.

here is the encoding & decoding process

-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
{

NSData *imageData=UIImagePNGRepresentation(self.imgViewProfilePicture.image);
[coder encodeObject:imageData forKey:@"PROFILE_PICTURE"];
[super encodeRestorableStateWithCoder:coder];
}

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{

self.imgViewProfilePicture.image=[UIImage imageWithData:[coder decodeObjectForKey:@"PROFILE_PICTURE"]];
[super decodeRestorableStateWithCoder:coder];

}

OTHER TIPS

To make the state preservation and restoration work there are two steps that are always required:

  • The App delegate must opt-in
  • Each view controller or view to be preserved/restored must have a restoration identifier assigned.

You should also implement encodeRestorableStateWithCoder: and decodeRestorableStateWithCoder: for views and view controllers that require state to be saved and restored.

Add the following methods to the view controller of your 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];
}

State preservation and restoration is an optional feature so you need to have the application delegate opt-in by implementing two methods:

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

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

Useful article about state preservation: http://useyourloaf.com/blog/2013/05/21/state-preservation-and-restoration.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top