如何保存通用度量< Unit>在核心数据中? [英] How to Save a Generic Measurement<Unit> in Core Data?

查看:42
本文介绍了如何保存通用度量< Unit>在核心数据中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在核心数据中保存和检索通用度量?

How does one save and retrieve a generic Measurement in Core Data?

我要保存的是 Measurement< UnitMass> Measurement< UnitVolume> .

在下面的图像中可以看到,CoreData设置为接受通用的 Measurement< Unit>

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.

我想念什么?

推荐答案

关于类型不匹配的错误在这里不是重要的部分.真正的问题是,可转换属性仅适用于符合 NSCoding 的类,或者您已为其编写了自己的自定义值转换器的类.由于 Measurement 不是类,并且不符合 NSCoding ,因此不能将其与可转换属性一起使用.

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.

您的选择是

  1. 在保存/读取属性值时,请勿保存 Measurement ,保存其值以及与 Measurement 进行转换.
  2. 编写您自己的 ValueTransformer 子类,该子类将在 Measurement Data 之间进行转换.
  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.

我会和#1一起去.您可以在托管对象子类上添加便捷方法来处理转换.

I'd go with #1. You could add convenience methods on your managed object subclass to handle the conversion.

更新:使用您的 Measurement< UnitMass> 案例,我会做类似的事情:

Update: Using your Measurement<UnitMass> case, I'd do something like:

  • 为该属性提供名为 massValue Double 属性.
  • 为该属性提供一个名为 massUnit 的可转换属性,该属性具有自定义类 UnitMass (请参见下文).
  • 使用以下方式保存值:

  • 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)")
    }
    

  • 这是配置 massUnit 属性的方式:

    这篇关于如何保存通用度量&lt; Unit&gt;在核心数据中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆