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 the Measurement
when saving/reading property values.
- Write your own custom subclass of
ValueTransformer
that will convert between Measurement
and Data
.
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 named massValue
.
- Give the attribute a transformable property named
massUnit
with custom class UnitMass
(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:
