Запишите код в метод AppDelegate для создания контекста управляемого объекта
lazy var applicationDocumentDirectory : URL = {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}()
lazy var manageObjectModel : NSManagedObjectModel = {
let modelUrl = Bundle.main.url(forResource: "CoreDataSample", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelUrl)!
}()
// MARK: - Базовый стек данных
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CoreDataSample")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
/ / MARK: - Базовые данные persistentStoreCoordinator
lazy var persistentStoreCoordinator : NSPersistentStoreCoordinator = {
let cordinator = NSPersistentStoreCoordinator(managedObjectModel: self.manageObjectModel)
let url = self.applicationDocumentDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error while creating and loading application's saved data"
do{
try cordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
}catch {
var dict = [String:Any]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSLog("Unresolved Error\(wrappedError),\(wrappedError.userInfo)")
abort()
}
return cordinator
}()
// MARK: - Базовый объект контекста данных
lazy var managedContextObject : NSManagedObjectContext = {
let cordinator = self.persistentStoreCoordinator
var managedContextObject = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedContextObject.persistentStoreCoordinator = cordinator
return managedContextObject
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
Сохранить данные
@IBAction func btnSaveClicked(_ sender: UIButton) {
let appDel : AppDelegate = UIApplication.shared.delegate as! AppDelegate
//creating managed object context
let context : NSManagedObjectContext = appDel.managedContextObject
let newUser = NSEntityDescription.insertNewObject(forEntityName: "UserDetails", into: context)
let data = self.imgP.pngData()
newUser.setValue(txtFname.text, forKey: "fName")
newUser.setValue(txtLname.text, forKey: "lName")
newUser.setValue(txtFTName.text, forKey: "fatherName")
newUser.setValue(txtEmail.text, forKey: "email")
newUser.setValue(txtPwd.text, forKey: "pwd")
newUser.setValue(txtCountry.text, forKey: "country")
newUser.setValue(txtState.text, forKey: "state")
newUser.setValue(txtCity.text, forKey: "city")
newUser.setValue(txtStreet.text, forKey: "street")
newUser.setValue(txtPinCode.text, forKey: "pin")
newUser.setValue(data, forKey: "img")
do{
try context.save()
}catch {
NSLog("Error while saving data")
}
}
Извлечение данных с использованием managedObject
func fetchData() {
let appDel : AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context : NSManagedObjectContext = appDel.managedContextObject
do{
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "UserDetails")
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
let obj = UserModel()
obj.firstName = data.value(forKey: "fName") as? String
obj.lastName = data.value(forKey: "lName") as? String
obj.fatherName = data.value(forKey: "fatherName") as? String
obj.Email = data.value(forKey: "email") as? String
obj.country = data.value(forKey: "country") as? String
obj.city = data.value(forKey: "city") as? String
obj.state = data.value(forKey: "state") as? String
obj.streetName = data.value(forKey: "street") as? String
obj.pinCode = data.value(forKey: "pin") as? String
obj.img = data.value(forKey: "img") as? NSData
arrData.add(obj)
}
} catch {
print("Failed")
}
}catch{
}
}`enter code here`