从 CoreData 中删除数据 [英] Delete data from CoreData

查看:41
本文介绍了从 CoreData 中删除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想马上说我是 Swift 的新手.我的任务是通过单击按钮删除某些数据附言单击按钮并删除框架",如何为此重写函数(在 SwiftUI、AppDelegate 中工作)

I want to say right away that I'm new to Swift. My task is to delete certain data by clicking on a button P.s. Clicked the button and removed the "frame", how to rewrite a function for this (Working in SwiftUI, AppDelegate)

//MARK: - PROPERTIES

    @FetchRequest(entity: TodoDB.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \TodoDB.name, ascending: true)]) var manyTasksTodo: FetchedResults<TodoDB>

实现了删除功能,但是在按钮动作中调用该功能时,出现错误

Implemented the delete function, but when you call the function in the button action, an error appears

//MARK: - FUNCTION

    public func deleteTodo(at offsets: IndexSet){
        for index in offsets{
            let todoDB = manyTasksTodo[index]
            managedObjectContext.delete(todoDB)
            do{
                try managedObjectContext.save()
            } catch{
                print(error)
            }
        }
    }

完整代码:

import SwiftUI

struct ContentView: View {
    //MARK: - PROPERTIES
    
    @Environment(\.managedObjectContext) var managedObjectContext
    
    @FetchRequest(entity: TodoDB.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \TodoDB.name, ascending: true)]) var manyTasksTodo: FetchedResults<TodoDB>
    
    @State public var AddTodo: Bool = false
    @State private var animationButton: Bool = false
    
    @Namespace var animationID
    
    //MARK: - BODY
    var body: some View {
            
        ScrollView(.vertical, showsIndicators: false){
            VStack{
                    ForEach(self.manyTasksTodo, id: \.self) { (todoDB: TodoDB) in

                        VStack(alignment: .leading, spacing: 5){
                            
                            ZStack{
                                Button(action: {
                                    
                                }, label: {
                                    Image(systemName: "trash")
                                        .frame(maxWidth: .infinity, alignment: .bottomTrailing)
                                        .padding(.bottom,30)
                                        .foregroundColor(.black)
                                })
                                
                            Divider()
                                
                                Text(todoDB.attribute ?? "unknown attribute")
                                    .foregroundColor(.black)
                                    .font(.callout)
                                    .padding(.bottom, 30)
                            }
                            Text(todoDB.name ?? "unknown task")
                                .foregroundColor(.black)
                                .padding(.bottom)
                            
                            
                            Text(todoDB.date ?? Date(), style: .date)
                                .foregroundColor(.black)
                                .font(.callout)
                                

                            HStack{     
                            Spacer() 
                            }
                        
                        }//VStack
                        .padding()
                        .background(Color("Red"))
                        .cornerRadius(10)
                        .padding()
                        
                    }//: FOREACH
                    
                    .onDelete(perform: deleteTodo(at:))
                    
                Spacer()

            }
            .shadow(color: Color.black.opacity(0.3), radius: 10, x: 0, y: 10)
            .shadow(color: Color.black.opacity(0.2), radius: 5, x: 0, y: 2)
        }
        .padding(.top, 45)
        .background(Color("Bg"))
        .edgesIgnoringSafeArea(.all)
        

            .overlay(
                ZStack{
                    Group{
                        Circle()
                            .fill(Color.black)
                            .opacity(self.animationButton ? 0.2 : 0)
                            .scaleEffect(self.animationButton ? 1 : 0)
                            .frame(width: 68, height: 68, alignment: .center)
                        Circle()
                            .fill(Color.black)
                            .opacity(self.animationButton ? 0.15 : 0)
                            .scaleEffect(self.animationButton ? 1 : 0)
                            .frame(width: 88, height: 88, alignment: .center)
                    }
                    .animation(Animation.easeInOut(duration: 2).repeatForever(autoreverses: true), value: self.animationButton)

                Button(action: {
                    self.AddTodo.toggle()

                }, label: {
                    Image(systemName: "plus.circle.fill")
                        .resizable()
                        .scaledToFit()
                        .background(Circle().fill(Color.white))
                        .foregroundColor(Color.black)
                        .frame(width: 48, height: 48, alignment: .center)
                    })

                .sheet(isPresented: $AddTodo){
                    AddTodoView().environment(\.managedObjectContext, self.managedObjectContext)}
                .onAppear(perform: {
                    self.animationButton.toggle()
                })

                }//: ZSTACK
                .padding(.bottom, 15)
                .padding(.trailing, 15)
                , alignment: .bottomTrailing
                )
            
        //}//: NAVIGATON
}
        
    
    
    //MARK: - FUNCTION
    
    public func deleteTodo(at offsets: IndexSet){
        for index in offsets{
            let todoDB = manyTasksTodo[index]
            managedObjectContext.delete(todoDB)
            do{
                try managedObjectContext.save()
            } catch{
                print(error)
            }
        }
    }
}

    //MARK: - PREIVIEW
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        let context  = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        return ContentView()
            .environment(\.managedObjectContext, context)
    }
}

推荐答案

IndexSet 方法在您使用 onDeleteForEach 时有效循环.

The IndexSet method works when you are using onDelete with a ForEach loop.

由于您无法使用 Button 访问 IndexSet,因此您传递了实际项目.

Since you don't have access to the IndexSet with a Button you pass the actual item.

将您的功能更改为此.

public func deleteTodo(todoDB: TodoDB){
        managedObjectContext.delete(todoDB)
        do{
            try managedObjectContext.save()
        } catch{
            print(error)
        }
}

然后将此代码放入垃圾箱按钮的操作中,如下所示.

And put this code within the trash button's action like this.

deleteTodo(todoDB: todoDB)

这篇关于从 CoreData 中删除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆