按对象ID删除对象 - 核心数据

时间:2016-11-21 17:30:37

标签: swift core-data swift3

我试图通过他的objectID删除我的数据库中的对象。 我知道是objectID(choosenID),它是由xcode创建的。

我做到了:

let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Notes")
request.predicate = NSPredicate(format: "objectID = %@", "\(choosenID)")
request.returnsObjectsAsFaults = false

    do {
        let results = try context.fetch(request)

        if results.count > 0 {

            for result in results as! [NSManagedObject] {

                print ("Note:")
                if let designation = result.value(forKey: "designation") {
                    print("Designation: \(designation)")
                }

                  context.delete(result)

                 do {
                     try context.save()
                 } catch {
                     print("failed to delete note")
                 }   
            }
        }
    } catch {
        print ("Error in do")
    }

如果我使用实体属性执行此类操作,则可以正常工作。但是使用objectID(NSManagedObjectID)它不起作用,应用程序崩溃。 有任何提示如何解决这个问题吗?

编辑:这是崩溃消息: “由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:'在实体中找不到keypath objectID'(...)libc ++ abi.dylib:以NSException类型的未捕获异常终止 (lldb)“

我看到我不能在谓词中使用objectID ....我试图使用SELF并且它不起作用....

0 个答案:

没有答案
相关问题