【问题标题】:Core Data computed property always returns 0Core Data 计算属性总是返回 0
【发布时间】: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


    【解决方案1】:

    把你的字符串改成

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

    "%.0f" 用于FloatDouble 你正在处理Int16

    【讨论】:

    • 嘿嘿...在所有愚蠢和基本的错误中,这必须赢得当天的奖项!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2016-03-30
    • 2012-10-28
    相关资源
    最近更新 更多