Database Reference
In-Depth Information
Go to the newly created CoreDataStack.swift and replace the contents of the file
with the following:
import CoreData
class CoreDataStack {
let context: NSManagedObjectContext
let psc: NSPersistentStoreCoordinator
let model: NSManagedObjectModel
let store: NSPersistentStore ?
}
These properties correspond to the stack components you read about in the
previous section. You aren't setting them to anything at the moment, so you should
be seeing warnings telling you that the Swift class is missing an initializer. Ignore
this warning for now—it will disappear in a few minutes.
Below the properties you just added, add the following method:
func applicationDocumentsDirectory() -> NSURL {
let fileManager = NSFileManager . defaultManager ()
let urls = fileManager. URLsForDirectory (. DocumentDirectory ,
inDomains: .UserDomainMask) as [ NSURL ]
return urls[ 0 ]
}
This is a simple helper method that returns a URL to your application's documents
directory. Why do you need this? You're going to store the SQLite database (which
is simply a file) in the documents directory. This is the recommended place to store
the user's data, whether or not you're using Core Data.
Now add the initializer method below the properties you declared earlier:
init () {
//1
let bundle = NSBundle . mainBundle ()
let modelURL =
bundle. URLForResource ( "Dog Walk" , withExtension: "momd" )
model = NSManagedObjectModel (contentsOfURL: modelURL!)
//2
psc = NSPersistentStoreCoordinator (managedObjectModel: model )
//3
context = NSManagedObjectContext ()
Search WWH ::




Custom Search