简体   繁体   English

保存到多个实体-核心数据-Swift

[英]Saving into multiple entities - Core Data - Swift

Hopefully this will make sense. 希望这会有意义。

I am trying to store data into 2 different entities from one function but not having much luck with storing data into the second entity. 我正在尝试将数据从一个函数存储到2个不同的实体中,但是将数据存储到第二个实体中并没有太多运气。

My 2 entities are called - Job & ShootKitChecklist . 我的2个实体称为- 工作ShootKitChecklist。

I have created a core data manager, I have stripped this back to just show you the section I am using: 我创建了一个核心数据管理器,将其剥离了一下,只是向您展示了我正在使用的部分:

struct CoreDataManager {

static let shared = CoreDataManager()

let persistentContainer: NSPersistentContainer = {
    // initialization of core data stack
    let container = NSPersistentContainer(name: "TBAShootCoreData")
    container.loadPersistentStores { (storeDescription, error) in
        if let error = error {
            fatalError("loading of store failed: \(error)")
        }
    }
    return container
}()

func createSKCItem(item: String, used: Bool, visible: Bool, job: Job) -> (ShootKitChecklist?, Error?) {
    let context = persistentContainer.viewContext
    // create Shoot kit item
    let SKC = NSEntityDescription.insertNewObject(forEntityName: "ShootKitChecklist", into: context) as! ShootKitChecklist

    SKC.job = job

    SKC.setValue(item, forKey: "item")
    SKC.setValue(used, forKey: "used")
    SKC.setValue(visible, forKey: "visible")

    do {
        try context.save()
        return (SKC, nil)
    } catch let error {
        print ("Failed to add Shoot Kit Item:", error)
        return (nil, error)
    }
}

} }

When I try to save the data, the Job entity ( First Entity )writes to the context and I can fetch it in another class. 当我尝试保存数据时,Job实体( First Entity )将写入上下文,并且可以在另一个类中获取它。

The data I am trying to save to the ShootKitChecklist is from an array so I put my setValues into a for look. 我试图保存到ShootKitChecklist的数据来自数组,因此我将setValues放入了外观。 However, it seems to ignore saving any data to the entity. 但是,似乎忽略了将任何数据保存到实体的操作。

var SKCequipment = ["A","B","C","D","E"]

@IBAction private func HandleSave(sender : UIButton) {



        let context = CoreDataManager.shared.persistentContainer.viewContext

        let job = NSEntityDescription.insertNewObject(forEntityName: "Job", into: context)
        let SKC = NSEntityDescription.insertNewObject(forEntityName: "ShootKitChecklist", into: context)

        job.setValue(jobBrandTextField.text, forKey: "jobBrand")
        job.setValue(jobNameTextField.text, forKey: "jobName")
        job.setValue(directorTextField.text, forKey: "directorName")
        job.setValue(agencyTextField.text, forKey: "agencyName")
        job.setValue(prodCoTextField.text, forKey: "prodCoName")


        for item in SKCequipment {
            print(item)
            SKC.setValue(item, forKey: "item")
            SKC.setValue(true, forKey: "used")
            SKC.setValue(true, forKey: "visible")
        }

        do {
            try context.save()
            dismiss(animated: true) {
                self.delegate?.didAddJob(job: job as! Job)
            }
        } catch let saveError {
            print("Failed to save company:", saveError)
        }
    }

To test to see if the items have been added to the core data I am fetching the items like this: 为了测试是否已将项目添加到核心数据中,我正在像这样提取项目:

guard let SKCitem = job?.skc?.allObjects as? [ShootKitChecklist] else { return}
self.skcitems = SKCitem
print(skcitems)

Thank you in advance, huge help! 在此先感谢您的大力帮助!

Okay I have fixed it by adding another function to my protocol and appending the Entity in the delegate(I realise that I didn't share this before (apologies). Here is my new protocol: 好的,我已经通过在协议中添加另一个功能并将Entity追加到委托中来修复它(我意识到我以前没有分享过这个(抱歉)。这是我的新协议:

protocol NewJobControllerDelegate {
    func didAddJob(job : Job)
    func didAddSKC(SKC : ShootKitChecklist)
}

And then in my HandleSave action I changed my for loop to this: 然后在HandleSave操作中,将for循环更改为:

for item in SKCequipment {
            let tuple = CoreDataManager.shared.createSKCItem(item: item, used: true, visible: true, job: job as! Job)
            if let error = tuple.1 {
                print("Cannot save items", error)
            } else  {
                self.delegate?.didAddSKC(SKC: tuple.0!)
            }

And finally my new function from my delegate: 最后是我的代表提供的新功能:

func didAddSKC(SKC: ShootKitChecklist) {
        ShootKit.append(SKC)
    }

Thank you for your help! 谢谢您的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM