问题描述:

I am using coreData in ios 8.0 and above. So I want to add the data to db.

I write below code in AppDelegate to support both iOS 10 and lower versions.

AppDelegate

// MARK: - Core Data Saving support

var context: NSManagedObjectContext?

func saveContext () {

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: "coreDataTestForPreOS", 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("coreDataTestForPreOS.sqlite")

do {

try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)

} catch {

fatalError("Error migrating store: \(error)")

}

}

}

}

let ad = UIApplication.shared.delegate as! AppDelegate

let context =

what should I write in context?

let ad = UIApplication.shared.delegate as! AppDelegate

let context =

Actually using that context I want to add data to db

func generateData() {

let item = Item(context: ) // which context is put here?

// to save data

ad.saveContext()

}

Any other method to support lower versions. Suggest me that too. Thanks in advance :-)

相关阅读:
Top