ios - 将结构作为核心数据实体的属性

标签 ios swift core-data

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

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 编辑器中以下属性的正确值是多少?

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

谢谢!

最佳答案

我会保存 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<T>使用半开式:0..<3包含 0 , 12


编辑

如果范围应该是可选的,那么如果 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
        }
    }
}

关于ios - 将结构作为核心数据实体的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47677908/

相关文章:

ios - 复杂的 NSPredicates : comparing values on the most-recent object

iphone - 使用核心数据存储对象

ios - 如何在iOS中动态创建Coredata实体和属性?

ios - 不兼容的指针类型将 User* 发送到 UserProfile* 类型的参数

iOS 15 : Enabling "Configure in App" option for notifications

ios - 解析、查询以根据频率查找对象

ios - 符合协议(protocol)和类的 Swift 属性

ios - 将 deviceToken 保存到 NSUserDefaults

ios - 对 coreData 数组中的真 bool 值求和

ios - Appium 不会更新它在列表元素和子元素中的 View