Database Reference
In-Depth Information
The first method is a simple convenience wrapper to determine whether the
persistent store is compatible with a given model. The second method helps by
retrieving the metadata for the store.
Next, add the following computed properties to the class:
lazy
var
storeURL :
NSURL
= {
var
storePaths =
NSSearchPathForDirectoriesInDomains
(
.
ApplicationSupportDirectory
, .UserDomainMask,
true
)
let
storePath = storePaths[
0
]
as
String
return
NSURL
.
fileURLWithPath
(
storePath.
stringByAppendingPathComponent
(
self
.
storeName
+
".sqlite"
))!
}()
lazy
var
storeModel :
NSManagedObjectModel
? = {
for
model
in
NSManagedObjectModel
.
modelVersionsForName
(
self
.
modelName
) {
if
self
.
storeIsCompatibleWith
(Model:model) {
println
(
"Store
\(
self
.
storeURL
)
is compatible with model
\(model.
versionIdentifiers
)
"
)
return
model
}
}
println
(
"Unable to determine storeModel"
)
return
nil
}()
These properties will allow you to access the current store URL and model. As it
turns out, there is no method in the CoreData API to ask a store for its model
version. Instead, the easiest solution is brute force. Since you've already created
helper methods to check if a store is compatible with a particular model, you'll
simply need to iterate through all the available models until you find one that works
with the store.
Next, you need your migration manger remember the current model version. Add a
property to the class, as follows:
lazy
var
currentModel:
NSManagedObjectModel
= {
// Let core data tell us which model is the current model
let
modelURL =
NSBundle
.
mainBundle
().
URLForResource
(
self
.
modelName
, withExtension:
"momd"
)
let
model =
NSManagedObjectModel
(contentsOfURL: modelURL!)
return
model
}()