Swift 3 - 具有一对多关系的核心数据保存

Mar*_*rco 4 core-data ios swift

我正在处理核心数据,我有两个实体:

游泳池参数 每个游泳池可以有多个参数

泳池与参数的关系

游泳池实体

参数实体

我已经保存并获取了游泳池的数据。

我已经通过表格保存了它们。

在我的 AppDelegate 中我有:

let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext
Run Code Online (Sandbox Code Playgroud)

这是函数:

 var swimmingpool: SwimminPool!

    if swimmingPoolToEdit == nil {
        swimming = SwimminPool(context: context)
    } else {
        swimming = swimmingPoolToEdit
    }

    if let name =  swimmingName.text {
        swimming.name = name
    }
    if let volume = swimmingVolume.text {
        swimming.volume = volume
.........................................................
ad.saveContext()
Run Code Online (Sandbox Code Playgroud)

我像这样执行获取:

var controller: NSFetchedResultsController<SwimmingPool>!

func attemptFetch() {

    let fetchRequest: NSFetchRequest<SwimminPool> = SwimminPool.fetchRequest()
    let dataSort = NSSortDescriptor(key: "createdAt", ascending: false)

    fetchRequest.sortDescriptors = [dataSort]

     let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

    controller.delegate = self
    self.controller = controller

    do {
        try controller.performFetch()
    } catch {
        let error = error as NSError
        print("\(error.debugDescription)")
    }
}
Run Code Online (Sandbox Code Playgroud)

通过一个segue,我将所有数据传递到一个新控制器,并通过一个新表单(在另一个控制器中)我试图保存参数数据并将它们连接到特定的游泳池。

我是否需要像为游泳池所做的那样保存数据,并且该关系将自动连接两个实体,或者我是否需要在保存时连接它们?

我是 swift 新手,不知道如何保存相关数据

连接将在保存时建立,或者当我执行参数获取时建立?

谢谢你!

小智 5

创建参数托管对象,然后将此参数链接到SwimingPool托管对象:

let parameter = Parameters(context: context)
parameter.chlorum = Double(12245454.12211) // insert your value
parameter.oxigen = "your value here"
parameter.createdAt = "your value here"

let swimming = SwimminPool(context: context)
swimming.parameter = parameter
ad.saveContext()
Run Code Online (Sandbox Code Playgroud)