In many iOS application development projects, we have requirement to store the data. We can store it in many ways, like in database or as a file storage in a document file. And if we have multiple types of data like text and image, we are storing them as different entities.
But can we store them as a single file? Yes, we can and here comes the NSFileWrapper to the rescue.
NSFileWrapper is a class that provides access to the contents of a file, directory or symbolic link. Using this class, multiple types of content can be saved as a single document and it can be loaded independently.
For example, if we have text and image then we can save them in a single document using NSFileWrapper and we can also extract image and text separately from it excluding the need to load the whole document.
Instances of NSFileWrapper is called file wrappers. They represent the file or directory as an object that can be displayed as image, can be saved to file system or even transmitted to another application.
There are 3 types of file wrappers,
1) Regular-file file wrapper
It contains the contents of a single actual file.
2) Directory file wrapper
It contains a directory and all the files and sub directories of that directory.
3) Symbolic-link file wrapper
It represents a symbolic link in the file system.
Now let’s see how we can use NSFileWrapper to save and load content of a document.
Consider we have to store text and an image in the document. So first we have to use subclass UIDocument which will deal with data saving into and fetching from NSFileWrapper.
In this class, we have to override 2 methods of UIDocument class.
Method to save the contents in the document file.
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
Method to read the contents of the document file.
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError