添加SwiftUI后删除核心数据项

时间:2020-05-22 00:31:19

标签: swift core-data swiftui

这是我的代码

咖啡结构和核心数据由NSManaged

import Foundation
import SwiftUI
import Combine

struct CoffeeItem: Identifiable{
    var id = UUID()
    var title: String
    var favorite: Bool
}

extension CoffeeItem {
    static func all() -> [CoffeeItem] {
        return [
            CoffeeItem(title: "Cappuccino", favorite: UserDefaults.standard.bool(forKey: "Cappuccino")),
            CoffeeItem(title: "Macchiato", favorite: UserDefaults.standard.bool(forKey: "Macchiato")),
            CoffeeItem(title: "Espresso", favorite: UserDefaults.standard.bool(forKey: "Espresso")),
            CoffeeItem(title: "Ristretto", favorite: UserDefaults.standard.bool(forKey: "Ristretto"))
        ]
    }
}

import CoreData

class CoffeeFavorite: NSManagedObject {
    @NSManaged var title: String
}

主视图

struct CoffeeSection: View {
    //Core Data
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(entity: CoffeeFavorite.entity(), sortDescriptors: [NSSortDescriptor(key: "title", ascending: true)]) var coffeeFavorite: FetchedResults<CoffeeFavorite>

    @State var coffeeItems = CoffeeItem.all()

    var body: some View {
        List {
            ForEach(0 ..< self.coffeeItems.count) { item in
                HStack {
                    Text(self.coffeeItems[item].title)
                        .fontWeight(.heavy)
                        .padding()

                    Spacer()

                    Image(systemName: self.coffeeItems[item].favorite ? "heart.fill" : "heart")
                        .padding()
                        .onTapGesture {
                            self.addItem(item: self.coffeeItems[item].title)
                            self.coffeeItems[item].favorite.toggle()
                            UserDefaults.standard.set(self.coffeeItems[item].favorite, forKey: self.coffeeItems[item].title)
                    }
                }
            }
        }
    }


    func addItem(item: String) {
        let newItem = CoffeeFavorite(context: managedObjectContext)
        newItem.title = item
        saveFavorites()
    }
    func saveFavorites() {
        do {
            try managedObjectContext.save()
        } catch {
            print(error)
        }
    }
}

收藏夹视图

struct FavoritesList: View {
    //Core Data
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(entity: CoffeeFavorite.entity(), sortDescriptors: [NSSortDescriptor(key: "title", ascending: false)]) var coffeeFavorite: FetchedResults<CoffeeFavorite>

    var body: some View {
        List {
            ForEach(coffeeFavorite, id: \.self) { item in
                Text(item.title)

            }
            .onDelete(perform: deleteItem)
        }
    }

    func deleteItem(indexSet: IndexSet) {
        let source = indexSet.first!
        let favorites = coffeeFavorite[source]
        managedObjectContext.delete(favorites)

        saveFavorites()
    }

    func saveFavorites() {
        do {
            try managedObjectContext.save()
        } catch {
            print(error)
        }
    }
}

我有一个主视图,其中有4个咖啡项目,右侧有一个心,点击该项目时,它将项目标题添加到核心数据中,并且可以在我最喜欢的视图中看到它。我可以使用.onDelete(perform:...)从收藏夹视图中删除我的核心项目,但是我想在主视图中通过点击心脏来做同样的事情,因此当我切换它时,我会从核心数据中添加并删除该项目。 如何在两个视图上同时工作?

1 个答案:

答案 0 :(得分:0)

要删除核心数据中所有与谓词匹配的项:

private func deleteFavorite(title: String) throws {
    let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "CoffeeFavorite")
    request.predicate = NSPredicate(format: "title == %@", title)
    try managedObjectContext.execute(NSBatchDeleteRequest(fetchRequest: request))
}