我试着用CoreData和SwiftUI创建一个小项目
我创建了两个简单的实体,一个名为机场,属性为icaoAPT,另一个称为简报,属性称为便笺
两者之间的关系,每一个机场都应该有许多注意事项。



在contentView上,我设法创建了一个列表,显示插入的所有机场
import SwiftUI
struct ContentView: View {
@Environment(\.managedObjectContext) var managedObjectContext
//Lista aeroporti
@FetchRequest(
entity: Airport.entity(),
sortDescriptors: [ NSSortDescriptor(keyPath: \Airport.icaoAPT, ascending: true) ]
) var apt: FetchedResults<Airport>
var body: some View {
NavigationView {
List{
ForEach(apt, id: \.self) { airp in
NavigationLink(destination: DeatailsView(briefing: airp)) {
HStack{
Text(airp.icaoAPT ?? "Not Avail")
}
}
}
}.navigationBarTitle(Text("Aeroporti"))
.navigationBarItems(trailing: NavigationLink(destination: AddView(), label: {
Text("add data")
}))
}
}
}在addview中,我将数据添加到机场实体中。
import SwiftUI
struct AddView: View {
@State var aptICAO : String = ""
@Environment(\.presentationMode) var presentation
@Environment(\.managedObjectContext) var dbContext
var body: some View {
VStack{
TextField("ICAO", text: self.$aptICAO)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(action: {
let newAirport = Airport(context: self.dbContext)
newAirport.icaoAPT = self.aptICAO
do {
try self.dbContext.save()
self.presentation.wrappedValue.dismiss()
} catch {
print("errore nel salva")
}
}) {
Text("Save")
}
}.padding()
}
}在detailsView上我想显示与那个机场有关的便条,但是我写的代码不起作用,我觉得我应该在detailsView上放一个NSFetch过滤那个机场的便条.但我不知道怎么写。
我的detailsView:
import SwiftUI
struct DeatailsView: View {
@Environment(\.managedObjectContext) var dbContext
@Environment(\.presentationMode) var presentation
@State var briefing : Airport
@FetchRequest(
entity: Briefing.entity(),
sortDescriptors: []) var noteAPT: FetchedResults<Briefing>
var body: some View {
VStack{
ForEach(noteAPT, id: \.self) { dt in
Text(dt.note ?? "Nt avail")
}
}
.navigationBarTitle( Text(briefing.icaoAPT ?? "apt not avail"))
.navigationBarItems(trailing: NavigationLink(destination: AddNote(airport: briefing), label: {
Text("add Note")
}))
}
}这里是我的AddNote视图:
struct AddNote: View {
@State var note : String = ""
@Environment(\.presentationMode) var presentation
@Environment(\.managedObjectContext) var dbContext
@State var airport : Airport
var body: some View {
VStack{
TextField("Note", text: self.$note)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(action: {
let newNOTE = Briefing(context: self.dbContext)
newNOTE.note = self.note
do {
try self.dbContext.save()
self.presentation.wrappedValue.dismiss()
} catch {
print("errore nel salva")
}
}) {
Text("Save Note for\(airport.icaoAPT ?? "NA")")
}
}.padding()
}
}我总是看到相同的音符,我对每个机场,但应该是不同的,在每个机场。
谢谢你的帮助
发布于 2020-07-03 13:30:01
如果你希望每个机场都有很多笔记,我建议你改变你的数据模型,这样它就能接受两者之间的“一对多”关系。
要回答主要问题;要能够进行筛选,需要根据所选机场的结果进行筛选。这个文章很好地解释了这一点,并使用NSPredicate进行了更详细的介绍。
https://stackoverflow.com/questions/62714608
复制相似问题