【问题标题】:Having a struct as an attribute of a core data entity将结构作为核心数据实体的属性
【发布时间】:2017-12-07 00:51:02
【问题描述】:

在我的核心数据模型中,我有一个实体,它的属性是一个结构。这是结构

struct Range: NSCoding {
    let minValue: Int
    let maxValue: Int

/* implementations of
    required init?(coder: NSCoder) 
   and
     func encode(with aCoder: NSCoder)
*/
}

为简洁起见,让我们想象一个这样的实体:

 Question
    -title: String
    -range: Range

我知道 range 属性需要是数据模型中的 Transformable。

当尝试将 Range 指定为可转换的类时,我收到 Property cannot be marked @NSManaged because its type cannot be represented in Objective-C 错误

什么是正确的设置?

更具体地说,Xcode 编辑器中以下属性的正确值是什么?

  • 价值转换器
  • 自定义类(我尝试将其设置为范围)
  • 模块(当前设置为“当前模块”)

谢谢!

【问题讨论】:

    标签: ios swift core-data


    【解决方案1】:

    我会将minValuemaxValue 保存为实体中的Int32

    @NSManaged var minValue: Int32
    @NSManaged var maxValue: Int32
    

    如果结构体使用简单版本(因为NSCoding 无论如何都不支持结构体)

    struct Range {
        let min: Int
        let max: Int
    }
    

    NSManagedObject(子)类中的计算属性将两个属性映射到Range对象

    var range : Range {
        get { return Range(min: Int(minValue), max: Int(maxValue)) }
        set {
            minValue = Int32(newValue.min)
            maxValue = Int32(newValue.max)
        }
    }
    

    或者忘记结构并使用真正的Range

    var range : Range<Int> {
        get { return Range<Int>(uncheckedBounds: (Int(minValue), Int(maxValue))) }
        set {
            minValue = Int32(newValue.lowerBound)
            maxValue = Int32(newValue.upperBound)
        }
    }
    

    考虑Range&lt;T&gt;使用半开类型:0..&lt;3包含012


    编辑

    如果该范围应该是可选的,那么您可以识别一个有效范围,例如 maxValue > minValue

    var range : Range<Int>? {
        get {
            guard maxValue > minValue else { return nil }
            return Range<Int>(uncheckedBounds: (Int(minValue), Int(maxValue))) }
        set {
            if let value = newValue {
                minValue = Int32(value.lowerBound)
                maxValue = Int32(value.upperBound)
            }  else {
                minValue = 0
                maxValue = 0
            }
        }
    }
    

    【讨论】:

    • 感谢您的建议。在我的模型中,范围是可选的,我想确保如果我有一个范围,它同时包含最小值和最大值。我的临时解决方案是使用 Range 实体来实现该效果。如果 Range 是一个类,它会让事情变得更容易吗?
    • 我添加了一个关于可选计算属性range的建议。
    • 我会记住您的解决方案,但我觉得有更好的方法将结构存储在核心数据实体中。
    • Transformable 用于符合Core Data 的值类型会不必要地昂贵。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多