SwiftUI核心数据删除实体的相关数据

时间:2020-07-04 12:44:28

标签: core-data swiftui relationship

im正在努力删除SwiftUI中的相关实体数据。 我有2个相关实体。
Bean(主体) 射击(相关实体) 多对一->每个豆都会有很多镜头

当我尝试构建和运行时,我得到了未解析bean的错误。

这是我的代码:

import SwiftUI

struct ShotList: View {
    
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: Bean.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Bean.name, ascending: true)]) var beans: FetchedResults<Bean>
    
    static let taskDateFormat: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        return formatter
    }()
    
    var body: some View {
        NavigationView {
            List {
                ForEach(beans, id: \.self) { bean in
                    Section(header: HStack {
                            Text(bean.wrappedName)
                            Text(bean.wrappedRoaster)}) {
                        ForEach(bean.shotArray, id: \.self) { shot in
                            HStack {
                                Text(shot.wrappedTaste)
                                Text(shot.wrappedTexture)
                                Text("\(shot.yield, specifier: "%.0f") g")
                                Text("\(shot.doseAmount, specifier: "%.0f") g")
                                Text("\(shot.bruRatio, specifier: "%.0f")")
                                Text("\(shot.time, specifier: "%.0f") s")
                                Spacer()
                                Text("\(shot.dateOfShot ?? Date(), formatter: ShotList.taskDateFormat)").font(.footnote)                                   
                            }                               
                        }.onDelete(perform: self.deleteShot)
                        .font(.body)
                    }
                }
            }.navigationBarTitle("Espresso Shotlist")
        }
    }
    
    func deleteShot(at offset: IndexSet) {
            for offset in offset {
                let shot = bean.shotArray[offset]
                moc.delete(shot)
            }
        try? moc.save()
    }      
}

struct ShotList_Previews: PreviewProvider {
    static var previews: some View {
        ShotList()
    }
}

1 个答案:

答案 0 :(得分:0)

bean仅在闭包中可访问:ForEach(beans,id:.self){bean in

在func deleteShot中将不可用。