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

时间:2016-11-07 17:49:06

标签: ios swift core-data

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

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

在我的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"

我没有收到任何错误,但是对象没有被删除..有人可以帮我弄清楚我做错了吗

1 个答案:

答案 0 :(得分:1)

context.delete(colorObject)

只是从内存中的颜色数组中删除颜色。您需要删除实际对象,例如

ArrayAdapter

并保存。