我有一个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)")
}
}
}
我有一个实体“产品”
:
我有一个 ViewController
,我插入了测试值:
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
}
}
我的问题是:
我设置了两次属性!一个在 ViewController.swift
中,另一个通过 manageObject.setValue
在 CoreDataHandler.swift
中。我只想设置一次并保存在数据库中!有办法这样做吗?我的项目中有超过 100 个属性的实体! CoreData 会帮助我实现此要求吗?
最佳答案
不,在 CoreDataHandler 类中,您只定义了一个“saveProduct”方法(函数)来保存值。该类本身不执行任何操作。
在 View Controller viewDidLoad 方法中,您必须创建 CoreDataHandler 的实例:
let handler = CoreDataHandler()
然后在您实例化的处理程序实例上调用“saveProduct”方法:
handler.saveProduct(...)
因此,您实际上只设置一次值,即在“viewDidLoad”期间在 View Controller 中设置值。
关于ios - 如何在 Swift 4 中使用 Core Data 保存数据而不写入两次值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49355607/