I have a DataHandler
:
import UIKit
import CoreData
class CoreDataHandler: NSObject {
private class func getContext() -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
class func saveProduct(p : [String: Any]) {
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: "Product", in: context)
let manageObject = NSManagedObject(entity: entity!, insertInto: context)
manageObject.setValue(p["default_code"], forKey: "default_code")
manageObject.setValue(p["name"], forKey: "name")
manageObject.setValue(p["id"], forKey: "id")
manageObject.setValue(p["display_name"], forKey: "display_name")
do {
try context.save()
print("Salvo com sucesso! \(String(describing: p["display_name"]))")
} catch {
print("Erro ao salvar: \(error.localizedDescription)")
}
}
}
I have an Entity "Product"
:
I have a ViewController
that I insert values for test:
class ViewController: UIViewController {
var products: [Product]? = nil
override func viewDidLoad() {
super.viewDidLoad()
print(NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as String)
var aux: [String:Any] = [:]
aux["name"] = "Nome do produto 4"
aux["default_code"] = "myDefaul_Code 4"
aux["id"] = 144
aux["display_name"] = "Nome para mostrar 4"
CoreDataHandler.saveProduct(p: aux)
products = CoreDataHandler.fetchObject()
for i in products! {
print(i.display_name!)
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private class func getContext() -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
}
My problem is:
I set the attributes two times! One in ViewController.swift
and other in the CoreDataHandler.swift
via manageObject.setValue
. I want to set it only once and save in the database? Is there a way to do so? I have entities in my project with more than 100 attributes! Will CoreData help me to implement this requirement?
Since you are using a dictionary you could make sure that the keys in the dictionary corresponds to the attribute names for your entity and then in the save func iterate over the dictionary
for (key, value) in p {
manageObject.setValue(value, forKey: key)
}
No, in the CoreDataHandler class you only defined a "saveProduct" method (function) to save the values. The class itself does nothing.
In your view controller viewDidLoad method you have to create an instance of the CoreDataHandler:
let handler = CoreDataHandler()
and then call that "saveProduct" method on the handler instance which you instantiated:
handler.saveProduct(...)
So you actually only set the values once, namely in your view controller during "viewDidLoad".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.