【发布时间】:2020-08-25 09:59:20
【问题描述】:
使用 SwiftUI
我创建了一个名为 SystemSettings 的 CoreData 实体,并希望使用其中存储的信息来计算不同视图上不同函数的结果,而无需使用 ForEach。 SystemSettings 将始终仅从预加载的数据库中存储一个对象(记录)。有没有办法我可以使用 @FetchRequest 并将唯一的对象及其属性作为 var.... 拉出?
谢谢
import SwiftUI
import CoreData
struct NewComponent: View {
@FetchRequest(entity: SystemSettings.entity(), sortDescriptors: []) var settings: FetchedResults<SystemSettings>
@Environment(\.managedObjectContext) var moc
@Environment(\.presentationMode) var presentationMode
var calculator = Calculator()
// USER DATA TEXT FIELDS
@State var parameterOne = "12.5"
@State var parameterTwo = "2.5"
@State var calculationResult = ""
var body: some View {
VStack {
Form {
Section (header: Text("Parameters").font(.headline).bold().italic()) {
HStack {
Text ("Length")
.font(.headline)
Spacer()
TextField ("m", text: $parameterOne).modifier(ClearButton(text: $parameterOne))
.multilineTextAlignment(.trailing)
.keyboardType(.decimalPad)
.font(.headline)
}
HStack {
Text ("Width")
.font(.headline)
Spacer()
TextField ("m", text: $parameterTwo).modifier(ClearButton(text: $parameterTwo))
.multilineTextAlignment(.trailing)
.keyboardType(.decimalPad)
.font(.headline)
}
}
}
Section(header:
Text("\(self.calculationResult)").bold().italic().padding(.top)
) {
Button(action: {
self.calculationResult = self.result()
}) {
HStack {
Spacer()
Image(systemName: "x.squareroot")
Text("Calculate!")
Spacer()
}.font(.headline).foregroundColor(Color.green)
.padding(.bottom, 40.0).padding(.top, 20.0)
}
}
}.navigationBarTitle(Text("Component Calculator"))
.gesture(DragGesture().onChanged{_ in UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)})
.modifier(KeyboardObserving())
.navigationBarItems(trailing: Button(action: {
let newEstimatedComponent = EstimatedComponents(context: self.moc)
newEstimatedComponent.name = "New Component"
newEstimatedComponent.price = self.priceToDisplay()
try? self.moc.save()
self.presentationMode.wrappedValue.dismiss()
}){Image(systemName: "checkmark.circle").font(.system(size: 30))})
}
func result () -> String {
let result = componentCost()
return (String(format: "%.2f",(result)) + " €")
}
func priceToDisplay() -> Double {
return componentCost()
}
func componentCost () -> Double {
return calculator (componentWidth: Double(parameterOne), componentHight: Double(parameterTwo), componentPrice: settings!.componentM2Price )
}
/*settings!componentM2Price not working of course, so I need to get the first and the only object from SystemSettings Entity in a way that I can use it in func componentCost()...*/
再次感谢...
【问题讨论】:
-
是的,它与获取所有元素的任何其他获取请求完全相同。考虑到您只有一条记录,也许您应该改用 UserDefaults?
-
欣赏评论,但是如何在非视图环境中使用 fetchedResults 呢?使用我在应用程序其他地方的不同视图中使用的函数进行类?我想使用核心数据,稍后它将连接到 cloudKit 和备份选项...谢谢
-
只需像在 SwiftUI 之前那样使用普通的 fetch 请求,所以基本上可以看到任何一年多的 Core Data 教程。鉴于您只有一个实例,也许您应该有一个用于访问和更新它的类