简体   繁体   中英

How to Save an Array of Custom Objects All At Once to a Core Data Store in Swift

I have a very similar question to: Swift: Store arrays of custom classes in Core Data

The difference is that question was looking to add to a custom class array in Core Data one element at a time. I am looking to add the entire array at once. When I try to, I get the following error: [CDTester.MassOfSubpart entity]: unrecognized selector sent to instance.

I made a simple app to demonstrate the error and hopefully figure out where I am going wrong. I uploaded it to GitHub here: https://github.com/Yrban/Core-Data-Test-App

The code where it crashes is here:

func saveWidget(){
    print("saveWidget() entered")
    if self.massOfSubpartMeasurementDict.count > 0,
        self.massOfSubpartMeasurementDict.count == self.numberOfSubparts,
        self.manufacturer != "",
        self.title != "" {

        var massPerSubpartMeasurementArray: [MassOfSubpart]
        massPerSubpartMeasurementArray = massOfSubpartMeasurementDict.map {
            return MassOfSubpart(subpart: $0.key, mass: Measurement(value: Double($0.value)!, unit: self.massUnit))
        }
        let massOfSubpartSet = Set(massPerSubpartMeasurementArray)

        let widget = Widget(context: self.managedObjectContext)
        widget.id = UUID()
        widget.madeBy?.name = self.manufacturer
        widget.hasMassOfPart = massOfSubpartSet // FIXME: The crash is here
        widget.title = self.title

        do {
            print("SaveWidget() attempted/n")
            try self.managedObjectContext.save()
        } catch {
            print("SaveWidget() failed/n")
            // handle the Core Data error
            // Show alert as to status
        }
    }
}

My Core Data model is:

核心数据模型

MassOfSubpart is a custom object:

import SwiftUI

public class MassOfSubpart: NSObject, Codable {

    var subPart: Int
    var mass: Measurement<UnitMass>

    override init() {
        self.subPart = 1
        self.mass = Measurement(value: 0.0, unit: UnitMass.grams)
    }

    init(subpart: Int, mass: Measurement<UnitMass>){
        self.subPart = subpart
        self.mass = mass
    }
}

I have read everything I could find, including Apple's documentation. I feel I am close, but I am obviously missing something important. Any help would be appreciated.

I finally figured out my error. I have not used relationships before, so it didn't dawn on me what I was doing. When I was accessing MassOfPartEntity through its relationship with Widget, I was sending a Set, my custom object through. However, I had to send a Set, the actual entity through. Therefore, I changed saveWidget to this:

func saveWidget(){
    print("saveWidget() entered")
    if self.massOfSubpartMeasurementDict.count > 0,
        self.massOfSubpartMeasurementDict.count == self.numberOfSubparts,
        self.manufacturer != "",
        self.title != "" {

        let massOfPartEntity = MassOfPartEntity(context: self.managedObjectContext)
        var massPerSubpartEntityArray: [MassOfPartEntity]
        massPerSubpartEntityArray = massOfSubpartMeasurementDict.map {
            massOfPartEntity.subPart = Int16($0.key)
            if let massDouble = Double($0.value) {
                massOfPartEntity.mass = Measurement(value: massDouble, unit: massUnit)
            } else {
                massOfPartEntity.mass = Measurement(value: 0.0, unit: massUnit)
            }
            return massOfPartEntity
        }
        let massOfSubpartSet = Set(massPerSubpartEntityArray) as NSSet

        let widget = Widget(context: self.managedObjectContext)
        widget.id = UUID()
        widget.madeBy?.name = self.manufacturer
        widget.addToHasMassOfPart(massOfSubpartSet) // FIXME: The crash is here
        widget.title = self.title

        do {
            print("SaveWidget() attempted/n")
            try self.managedObjectContext.save()
        } catch {
            print("SaveWidget() failed/n")
            // handle the Core Data error
            // Show alert as to status
        }
    }
}

changing the Map function return so that it returned MassOfPartEntity's that eventually became a Set. Essentially, it was a type mismatch.

Thanks to those who responded as talking it out definitely helped resolve this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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