问题
How does one save and retrieve a generic Measurement in Core Data?
What I'm looking to do is save either a Measurement<UnitMass>
or a Measurement<UnitVolume>
.
As can be seen in the image below CoreData is set to accept a Generic Measurement<Unit>
However I'm getting an error when I go to set the value of the measure. Saying that I'm not allowed to do this. I thought the purpose of generics was to support uses like this.
What am i missing?
回答1:
The error about mismatched types isn't the important part here. The real problem is that transformable attributes only work with classes that conform to NSCoding
or for which you've written your own custom value transformer. Since Measurement
is not a class and does not conform to NSCoding
, you can't use it with a transformable attribute.
Your options are
- Don't save the
Measurement
, save its values, and convert to/from theMeasurement
when saving/reading property values. - Write your own custom subclass of
ValueTransformer
that will convert betweenMeasurement
andData
.
I'd go with #1. You could add convenience methods on your managed object subclass to handle the conversion.
Update: Using your Measurement<UnitMass>
case, I'd do something like:
- Give the attribute a
Double
property namedmassValue
. - Give the attribute a transformable property named
massUnit
with custom classUnitMass
(see below). Save values with something like this:
let servingMeasure = Measurement<UnitMass>(value:500, unit:.grams) myObject.massValue = servingMeasure.value myObject.massUnit = servingMeasure.unit
Retrieve values with something like:
if let unit = myObject.massUnit { let value = myObject.massValue let measurement = Measurement<UnitMass>(value:value, unit:unit) print("Measurement: \(measurement)") }
This is how the massUnit
property is configured:
回答2:
In Swift, Measurement does adopt the code able protocol, and therefore it can be saved in Core Data through a transformable attribute.
The error that you got is actually pretty clear. You can't save a specific Measurement type Measurement<UnitMass>
to the generic type Measurement<Unit>
in Core Data. You can't do it in the main code, either. The fix is simple, for each attribute specify the specific type for that attribute as the Custom Class.
来源:https://stackoverflow.com/questions/48522897/how-to-save-a-generic-measurementunit-in-core-data