ios - 如何在 Swift 4 中使用 Core Data 保存数据而不写入两次值?

标签 ios swift xcode core-data

我有一个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)")
        }
    }
}

我有一个实体“产品”:

enter image description here

我有一个 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.setValueCoreDataHandler.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/

相关文章:

ios - 如何将变量设置为从 0 开始并通过嵌套 for 循环 Swift 2 中的每个循环获得一个级别

iphone - "May not respond to "警告

ios - 我在 View 类中编写了一个tableView,但它无法显示数据源

iphone - 如何在 UITableViewCell 的子类中管理旋转

ios - 不寻常的 CoreMotion Sensorfusion 数据

swift - 如何使用 PromiseKit 重构快速回调以实现 Promise

ios - 延迟出列可重复使用的单元格

ios - 有没有办法仍然使用 XCode 4 在 iPhone 5s 上运行

xcode - 我可以更改 Xcode IDE 字体的大小吗?

xcode - 如何在 Xcode 中查看详细的错误消息 "Apple Mach -O Linker Error"?