iPhone - save UIImageView state

2020-03-30 03:23发布

问题:

I have created a subclass of UIImageView and I am handling the touches for its objects inside the subclass itself.

Now when the user is about to exit the app I want to save the state of the images. And as there are multiple transforms which might have taken place on the images (I am saving all the transforms in an array), I want to be able to save these objects in applicationWillTerminate.

Is there any way I can save these objects? Or do I have to save everything individually? If I do, how do I save all the transformations which have happened on the image view objects till the user exits?

Thanks.

回答1:

UIImageView conforms to NSCoding. You will need to implement encodeWithCoder: in your UIImageView subclass to allow it to be serialised. You use the passed encoder to serialise the important member variables, in this case your images then call the superclass' encodeWithCoder:.

You do the the inverse of this in initWithCoder: an you've got your original state back.

If your images are instances of UIImage you'll have a bit more work to do since it doesn't conform to NSCoding. You might be able to get away with converting the image data to an NSData object and encoding that depending on your requirements. Here's an example of how this can be done: http://www.nixwire.com/getting-uiimage-to-work-with-nscoding-encodewithcoder/

Have a look at the Archives and Serializations Programming Guide for Cocoa: http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/Archiving/Archiving.html