Database Reference
In-Depth Information
The only reason
SurfJournalDatabase.sqlite
,
SurfJournalDatabase.sqlite-shm
or
SurfJournalDatabase.sqlite-wal
would fail to copy over on first launch is if
something really bad happened, such as disk corruption from cosmic radiation. In
that case the device, including any apps, would likely also fail. If the app won't
work, there's no point in continuing, so the initializer calls
abort
.
Note:
We developers often frown upon using
abort
, as it confuses users by
causing the app to quit suddenly and without explanation. But this is one
example where
abort
is acceptable, since the app needs Core Data to work.
If an app requires Core Data to be useful and Core Data isn't working, there's
no point in letting the app continue on, only to fail sometime later in a non-
deterministic way. Calling
abort
at least generates a stack trace, which can be
helpful when trying to fix the problem.
If your app has support for remote logging or crash reporting, you should log
any relevant information that might be helpful for debugging before calling
abort
.
Once the initializer has copied over the pre-populated database and support files,
the final step is to add the seeded database store to the persistent store
coordinator.
// 6
var
error:
NSError
? =
nil
let
options = [
NSInferMappingModelAutomaticallyOption
:
true
,
NSMigratePersistentStoresAutomaticallyOption
:
true
]
store
=
psc
.
addPersistentStoreWithType
(
NSSQLiteStoreType
,
configuration:
nil
,
URL: storeURL,
options: options,
error: &error)
// 7
if
store
==
nil
{
println
(
"Error adding persistent store:
\(error)
"
)
abort
()
}
6.
NSPersistentStoreCoordinator
hands you an
NSPersistentStore
object as a side
effect of attaching a persistent store type. You simply have to specify the store
type (
NSSQLiteStoreType
in this case), the URL location of the store file and some
configuration options.
7. Finally, the initializer checks if the store was successfully created. If it wasn't, the
app won't work, so there's no point in continuing; the initializer calls
abort
.