[英]How to save data using CoreData without write values two times on Swift4?
我有一個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)")
}
}
}
我有一個Entity "Product"
:
我有一個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
中,另一個在CoreDataHandler.swift
中通過manageObject.setValue
。 我只想設置一次並保存在數據庫中? 有辦法嗎? 我的項目中有超過 100 個屬性的實體! CoreData會幫我實現這個需求嗎?
由於您使用的是字典,因此您可以確保字典中的鍵對應於實體的屬性名稱,然后在保存函數中迭代字典
for (key, value) in p {
manageObject.setValue(value, forKey: key)
}
不,在 CoreDataHandler 類中,您只定義了一個“saveProduct”方法(函數)來保存值。 類本身什么也不做。
在您的視圖控制器 viewDidLoad 方法中,您必須創建 CoreDataHandler 的實例:
let handler = CoreDataHandler()
然后在您實例化的處理程序實例上調用該“saveProduct”方法:
handler.saveProduct(...)
所以你實際上只設置了一次值,即在“viewDidLoad”期間在你的視圖控制器中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.