Core data 是否要在核心数据中存储系统设置

Core data 是否要在核心数据中存储系统设置,core-data,swiftui,Core Data,Swiftui,使用SwiftUI 我已经创建了一个名为SystemSettings的CoreData实体,并希望使用其中存储的信息来计算不同视图上不同函数的结果,而无需使用ForEach。SystemSettings将始终仅从预加载的数据库存储一个对象(记录)。是否有一种方法可以使用@FetchRequest并提取出唯一的对象及其属性,作为变量 多谢各位 import SwiftUI import CoreData struct NewComponent: View { @Fet

使用SwiftUI

我已经创建了一个名为SystemSettings的CoreData实体,并希望使用其中存储的信息来计算不同视图上不同函数的结果,而无需使用ForEach。SystemSettings将始终仅从预加载的数据库存储一个对象(记录)。是否有一种方法可以使用@FetchRequest并提取出唯一的对象及其属性,作为变量

多谢各位

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()...*/

导入快捷界面
导入CoreData
结构新组件:视图{
@FetchRequest(实体:SystemSettings.entity(),sortDescriptors:[])变量设置:FetchedResults
@环境(\.managedObjectContext)变量moc
@环境(\.presentationMode)变量presentationMode
变量计算器=计算器()
//用户数据文本字段
@状态变量参数one=“12.5”
@状态变量参数two=“2.5”
@State var calculationResult=“”
var body:一些观点{
VStack{
形式{
节(标题:文本(“参数”).font(.headline).bold().italic()){
HStack{
文本(“长度”)
.font(.headline)
垫片()
文本字段(“m”,文本:$parameterOne)。修饰符(ClearButton(文本:$parameterOne))
.multilitextalignment(.training)
.键盘类型(.decimalPad)
.font(.headline)
}
HStack{
文本(“宽度”)
.font(.headline)
垫片()
TextField(“m”,text:$parameterTwo).修饰符(ClearButton(text:$parameterTwo))
.multilitextalignment(.training)
.键盘类型(.decimalPad)
.font(.headline)
}
}
}
节(标题:
文本(\(self.calculationResult)).bold().italic().padding(.top)
) {
按钮(操作:{
self.calculationResult=self.result()
}) {
HStack{
垫片()
图像(系统名称:“x.平方根”)
文本(“计算!”)
垫片()
}.font(.headline).foregroundColor(Color.green)
.padding(.bottom,40.0)。padding(.top,20.0)
}
}
}.navigationBarTitle(文本(“组件计算器”))
.signer(DragGesture().onChanged{inUIApplication.shared.sendAction(#选择器(UIResponder.resignFirstResponder),to:nil,from:nil,for:nil)})
.修饰符(键盘()
.navigationBarItems(尾部:按钮(操作:{
让newEstimatedComponent=EstimatedComponents(上下文:self.moc)
newEstimatedComponent.name=“新组件”
newEstimatedComponent.price=self.priceToDisplay()
试试?self.moc.save()
self.presentationMode.wrappedValue.discouse()文件
}){Image(systemName:“checkmark.circle”).font(.system(大小:30))}
}
func result()->String{
让结果=组件成本()
返回值(字符串(格式:“%.2f”,(结果))+“€”)
}
func priceToDisplay()->Double{
返回组件成本()
}
func componentCost()->Double{
返回计算器(componentWidth:Double(参数一),componentHight:Double(参数二),componentPrice:settings!.componentM2Price)
}
/*设置!componentM2Price当然不起作用,因此我需要从SystemSettings实体中获取第一个也是唯一一个对象,以便在func componentCost()中使用它*/
再次感谢…

问题解决了

@EnvironmentObject var settings: ModifySystemSettings
let systemSettings: SystemSettings
您可以在此处找到更多信息: 解决了

@EnvironmentObject var settings: ModifySystemSettings
let systemSettings: SystemSettings
您可以在此处找到更多信息:

是的,它将与获取所有元素的任何其他获取请求完全相同。考虑到您只有一条记录,也许您应该改用UserDefaults?感谢您的评论,但我如何在非视图环境中使用fetchedResults?类中包含我在应用程序其他地方的不同视图中使用的函数?我想使用core数据,稍后它将连接到cloudKit和备份选项…感谢您必须像SwiftUI之前那样使用它作为正常的获取请求,因此基本上可以看到任何一个超过一年的核心数据教程。鉴于您只有一个实例,您可能应该有一个单独的类来访问和更新它。是的,它将完全相同s获取所有元素的任何其他获取请求。考虑到您只有一条记录,也许您应该改用UserDefaults?感谢您的评论,但我如何在非视图环境中使用fetchedResults?使用我在应用程序其他地方的不同视图中使用的函数初始化?我想使用核心数据,稍后将连接它对于cloudKit和备份选项…感谢您必须像SwiftUI之前那样使用它作为正常的获取请求,所以基本上可以看到任何一个超过一年的核心数据教程。如果您只有一个实例,那么您应该有一个类来访问和更新它