【发布时间】:2021-07-06 21:42:04
【问题描述】:
我正在学习 SwiftUI 并创建一个非常简单的应用程序,其中一些 Ints 在一个屏幕上输入 (Itemsheet),计算在 app.xcdatamodel 中运行,它们在 ContentView 上输出。
但是,计算出来的值让我抓狂。它似乎总是显示为 0。我很想知道是否有人知道为什么?
这是我的代码:
ItemSheet.swift
@Environment(\.managedObjectContext) private var viewContext
Stepper("\(days) days", value: $days)
Stepper("\(cost)€", value: $cost)
app.xcdatamodel
extension Pricing {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Pricing> {
return NSFetchRequest<Pricing>(entityName: "Pricing")
}
@NSManaged public var days: Int16
@NSManaged public var cost: Int16
public var costPerDay: String {
get {
if (self.cost > 0) {
let newValue = String(format: "%.0f", "Cost per day: \(cost) / \(days)")
return newValue
}
else {
return "add cost"
}
}
set {
self.costPerDay = newValue
}
}
}
ContentView.swift
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(entity: Clothing.entity(), sortDescriptors: [])
var clothing: FetchedResults<Clothing>
var body: some View {
ForEach(clothing) { item in
Text("Days: \(item.days)")
Text("Cost: \(item.cost)")
Text("Cost per Days: \(item.costPerDay)")
}
}
}
其他两个文本视图(Text("Days: \(item.days)")和Text("Cost: \(item.cost)"))工作正常,所以我猜我在某处的核心数据模型中犯了一个新手错误?
谢谢!
【问题讨论】:
标签: core-data swiftui computed-properties