ios - 如何删除 managedObject - 而不是 tableView

标签 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"

我没有收到任何错误,但对象没有被删除。有人能帮我弄清楚我做错了什么吗

最佳答案

colors.remove(at: i)

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

context.delete(colorObject)

并保存。

关于ios - 如何删除 managedObject - 而不是 tableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40471388/

相关文章:

ios - 如何从 iOS/swift 中的闭包函数返回值?

ios - Bundle.main.url(forResource : "hello", withExtension: "html") 返回 nil

core-data - Swift 3 核心数据 - 获取结果 Controller

ios - 选择 UIButton 时,这个按钮人工制品是什么?

ios - swift alamofire 异步请求 json

ios - UITapGestureRecognizer 不工作 - Swift 2

macos - 如何强制 NSArrayController 重新加载 MOC 内容以反射(reflect)最新的数据

swift - 关于核心数据保存对象的主要实体与次要实体

ios - 是否可以将多个公钥保存到 ios 中的钥匙串(keychain),swift

swift - 执行被中断,原因: EXC_BAD_ACCESS - Swift Literals