Database Reference
In-Depth Information
When you first launched the app, it already had a significant amount of data. While
the projects in some of the previous chapters import seed data from a JSON file,
this sample project comes with a seeded Core Data database. Let's see how it
works.
The Core Data stack
Open CoreDataStack.swift and find the following code in init :
// 1
let seededDatabaseURL = b undle
. URLForResource ( "SurfJournalDatabase" ,
withExtension: "sqlite" )
// 2
var fileManagerError: NSError ? = nil
let didCopyDatabase = NSFileManager . defaultManager ()
. copyItemAtURL (seededDatabaseURL!, toURL: storeURL,
error: &fileManagerError)
// 3
if didCopyDatabase {
As you can see, this chapter's version of CoreDataStack.swift is a little different.
Let's go through the differences step by step:
1. The app bundle comes with a pre-populated Core Data database named
SurfJournalDatabase.sqlite . To make use of this database, first you have to
find it and create a URL reference to it using URLForResource(_:withExtension:) .
2. copyItemAtURL(_:toURL:error:) attempts to copy the seeded database file to the
app's documents directory. If the database file already exists in the documents
directory, the copy operation fails. This behavior allows the seeding operation to
happen only once, on first launch.
3. On subsequent app launches, the database will already exist and the copy will
fail. When the copy operation fails, the variable didCopyDatabase will be false
and the code in the if -statement will never execute.
Search WWH ::




Custom Search