核心数据计算 属性 总是 returns 0
Core Data computed property always returns 0
我正在学习 SwiftUI 并创建一个非常简单的应用程序,其中一些 Int 在一个屏幕上输入 (Itemsheet
),计算是 运行 in 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)")
)都工作正常,所以我猜我在核心数据模型的某个地方犯了新手错误?
谢谢!
将您的字符串更改为
String(format: "Cost per day: %.0f", Double(cost / days))
"%.0f"
用于 Float
或 Double
你正在处理 Int16
我正在学习 SwiftUI 并创建一个非常简单的应用程序,其中一些 Int 在一个屏幕上输入 (Itemsheet
),计算是 运行 in 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)")
)都工作正常,所以我猜我在核心数据模型的某个地方犯了新手错误?
谢谢!
将您的字符串更改为
String(format: "Cost per day: %.0f", Double(cost / days))
"%.0f"
用于 Float
或 Double
你正在处理 Int16