How to output a view hierarchy & contents to file?

2019-09-14 15:11发布

问题:

I'm writing a glorified 'paint' application where a user can paste in images, and draw a bunch of UIBezier curves, and move all these things around and rotate them.

Most of these are implemented by stacking UIImageViews and (sub-classed) UIViews as subviews onto the main view in the view controller.

I want the user to be able to save the state of their creation as some kind of file and share it with others (e.g. via DropBox).

The saving itself isn't the issue (I know how to save files!), just the 'best' way to get all the information from the app into file(s) and then load it back in.

I'm guessing there are already well-established frameworks for doing exactly this, but oddly, haven't found anything that addresses this.

So, before I set about writing my own custom methods for doing all this, I thought I'd ask:

Is there some recommended, approved (and maybe even 'easy' ;-)) way to implement saving -- as in writing to files -- the state of all the subviews of a given UIView?

Your recommendations for what I'm "trying to do"? Thanks.

回答1:

tl;dr

Going Down:
NSKeyedArchiver.archiveRootObject(view, toFile: "/path/to/archive")

Coming Up:
let view = NSKeyedUnarchiver.unarchiveObjectWithFile("/path/to/archive")

)

UIView conforms to NSCoding

NSCoding enables the creation of archives, which

provide a means to convert objects and values into an architecture-independent stream of bytes.

Now we have all the pieces to the puzzle, let's put them together:

We know we're going to need an archiver, so let's search the docs until we find something promising:

Bingo! NSKeyedArchiver

Let's use this class to serialize a UIView to a file with archiveRootObject:toFile:. Then we'll deserialize it from a file with unarchiveObjectWithFile:.

Saving to file:
NSKeyedArchiver.archiveRootObject(view, toFile: "/path/to/archive")

Reading from file:
let view = NSKeyedUnarchiver.unarchiveObjectWithFile("/path/to/archive")