gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:07:57 30 4
gpt4 key购买 nike

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

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com