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.