首页 > 解决方案 > Core Data 计算属性总是返回 0

问题描述

我正在学习 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
        }
    }
}

内容视图.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 视图 (Text("Days: \(item.days)")Text("Cost: \(item.cost)")) 都工作正常,所以猜测我在某处的核心数据模型中犯了一个新手错误?

谢谢!

标签: core-dataswiftuicomputed-properties

解决方案


将您的字符串更改为

String(format: "Cost per day: %.0f",  Double(cost / days))

"%.0f"是为了Float或者Double你正在处理Int16


推荐阅读