iOS: How can I create a backup copy of my core data base? And how to export/import that copy?

前端 未结 3 1826
盖世英雄少女心
盖世英雄少女心 2021-01-31 12:42

I want to offer the users of my app the possibility to create a backup of the core data database, especially in case he switches to a new device etc.

How would I do that

3条回答
  •  野性不改
    2021-01-31 13:18

    Whatever the persistent store is that you use (binary, SQLite, etc.); it is just a file on the filesystem. You can make a copy of it whenever you want.

    If you are using SQLite in iOS 7, be sure to make a copy of the other files associated with it as they are the journal files that go with it. If you are using binary then there will be only a single file.

    If you just copy the file there is no import step, you just copy it back to restore it.

    There are more advanced designs such as exporting the entire database to something that is portable, such as JSON but that is a different subject.

    Update

    Well I've used the standard Xcode core data template, so according to the code I've just checked I'm using SQLite. So how do I find all related files? Or could you show me with some example code how to copy and insert back the files needed?

    You use NSFileManager to copy the files. You can look at the documents directory in your iOS simulator application to see the names of all the files. Or you could use NSFileManager to scan the documents directory, find everything that starts with the same file name (MyData.* for example) and copy that into a back up directory.

    As for sample code, no; it is only a couple of lines of code once you look at the documentation for NSFileManager.

提交回复
热议问题