如何删除托管对象 - 而不是 tableView

问题描述 投票:0回答:1

我正在核心数据图中描述一些颜色信息。实体是颜色,属性是颜色分量。

我在两个方面苦苦挣扎:如何从图表中删除颜色对象,其次,(额外问题?),我如何识别重复的颜色?

在我的 AppDelegate 中,我有一个像这样的核心数据堆栈:

lazy var persistentContainer: NSPersistentContainer = {
        
        let container = NSPersistentContainer(name: "DD")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replacing this implementation with code to handle the error appropriately.
                
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()
    
    // MARK: - Core Data Saving support
    
    func saveContext () {
        print(#function)
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

在我尝试删除颜色的地方,我有这个:

func deleteColor(_ sender:UIButton) {
        
        let i : Int = (sender.layer.value(forKey: "index")) as! Int
        print(#function, "object to delete: ", i)
        
        let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        
        colors.remove(at: i)
        
        do {
            try managedContext.save()
        } catch let error as NSError  {
            print("Error While Saving Data: \(error.userInfo)")
        }
        
        recentColorCollection!.reloadData()     
    }
    

变量是:

var colors = [RecentColorEntity]()
    var colorEntity = "RecentColorEntity"

我没有收到任何错误,但对象没有被删除。我做错了什么?

ios swift core-data
1个回答
1
投票
colors.remove(at: i)

只是从内存中的颜色数组中删除颜色。您需要删除实际对象,就像这样

context.delete(colorObject)

并保存。

© www.soinside.com 2019 - 2024. All rights reserved.