How to Save a Generic Measurement<Unit> in Core Data?

十年热恋 提交于 2021-02-07 09:28:57

问题


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

  1. Don't save the Measurement, save its values, and convert to/from the Measurement when saving/reading property values.
  2. 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:




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!