James Amo's solution gives you the most features for iOS 10.0, but does not apply to iOS 9.0 and below, which cannot access this method and you need to manually create NSManagedObjectModel . Here is the solution that worked for me:
var context: NSManagedObjectContext? if #available(iOS 10.0, *) { context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext } else { // iOS 9.0 and below - however you were previously handling it guard let modelURL = Bundle.main.url(forResource: "Model", withExtension:"momd") else { fatalError("Error loading model from bundle") } guard let mom = NSManagedObjectModel(contentsOf: modelURL) else { fatalError("Error initializing mom from: \(modelURL)") } let psc = NSPersistentStoreCoordinator(managedObjectModel: mom) context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let docURL = urls[urls.endIndex-1] let storeURL = docURL.appendingPathComponent("Model.sqlite") do { try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil) } catch { fatalError("Error migrating store: \(error)") } }
Clearly, changing to 10.0 makes CoreData much easier, but unfortunately, it hurts so much for existing developers to make the jump ...
To implement the above, just make sure you select persistentContainer in your AppDelegate.swift specified in James Amo .
legel Sep 21 '16 at 21:46 2016-09-21 21:46
source share