Search code examples
iosswiftcore-datansfilemanageruidocument

Is it possible to use Core Data in a document-based application?


I'm working on an iOS app that will need to save data onto files. I chose to go for a Document Based app, precisely an app based on a UIDocumentBrowserViewController so that I can easily save and load files from the system's Files app.

Since the data I need to save/load on a file is quite complex: big hierarchy of different objects, with meta-data, image files, etc. I'm wondering what is the best technology to use going forward. I came across NSFileWrapperand its ability to save different files as one. And I could definitely use that. But I also saw UIManagedDocument and the ability to use Core Data in my project while maybe saving the content of the Core Data database (I know it's not quite a database, but you know what I mean) into a file that I could write somewhere in the File App.

Is this a behavior I can expect?

To reformulate: I'm wondering if I can read/write files through a UIDocumentBrowserViewController, with data described by a UIManagedDocument that works with Core Data.

Thank you in advance. 🙂


Solution

  • As you have discovered, UIManagedDocument is there for your kind of application. And it does feature methods to write and read additional content like the metadata or image files you have, within the document package.

    That being said, I have never used UIManagedDocument, and have never seen it used by others. A quick search of GitHub finds only this one project with two contributors who wrote a wrapper around it in 2013. Also, there does not seem to be any sample code from Apple, and the remark in the the writeAdditionalContent(_:to:originalContentsURL:) documentation that Additional content is not supported on iCloud leaves me a little concerned, but maybe it's a good sign that the Core Data team knows where to draw the line.

    I have used the macOS counterpart of UIManagedDocument, NSPersistentDocument. It is in a similar situation of not being used very much, but with many more known technical issues. So a few years ago I switched to BSManagedDocument, which purportedly mimics UIManagedDocument to support Core Data in all its modern glory. I have been happy with BSManagedDocument.

    In summary, if I was in your situation, yes I would give UIManagedDocument a try. But don't be surprised if you need to use a DTS support incident or two during your development.