Archiving UIImageView with NSCoding

2019-08-08 19:29发布

问题:

I've never used NSCoding before and I'm very confused about how it should be implemented.

My current iPad app has a UIImageView (called "background") which is a property of my main view controller. "background" has a UIImage "image" property (obviously) and various subviews which are added by the user. The added subviews are my own custom subclasses of UIImageView.

I need to be able to save the state of the "background" UIImageView so it can be restored with the same image and all the subviews in place as it was when archived.

I understand UIImageView conforms to the NSCoding protocol, but I'm not sure where to implement encodeWithCoder and initWithCoder. Do I call these from my main view controller? Do I need to create a category for UIImageView which allows me to override these methods?

Do I need to write code for archiving every property of my "background" UIImageView and its subviews? I have read elsewhere on SO that UIImage does not conform to NSCoding so needs to be subclassed or have a category added in order to be able to archive UIImageView.

I thought there would be a simple way to save to disk an object including all its properties, subviews etc. It seems there's a lot that needs to be done in order for me to save this "background" UIImageView and restore it later. I'm struggling to visualise everything I need to do. Any pointers much appreciated!

回答1:

Serialization (aka archiving and unarchiving) is actually pretty complicated, but the degree to which Cocoa makes it easy is a pretty impressive feat.

Once you've set things up so that the UIImageView and all of its properties that you want to keep conform to NSCoding, then all you have to do to save the object is:

NSData *dataToSave = [NSKeyedArchiver archivedDataWithRootObject:yourImageView];

And then store that NSData somewhere. Then, to unarchive the object,

UIImageView *restoredImageView = [NSKeyedUnarchiver unarchiveObjectWithData:dataToRestore];

after recovering the NSData from somewhere.

As for making everything conform to NSCoding, UIImageView conforms to NSCoding, as does UIView, so between your UIImageView, its subviews, and their properties, everything probably conforms to NSCoding except for the actual UIImage. For that, if you google you can find lots of categories people have made to make it conform to NSCoding, so just include one of them in your project and you should be fine.