Swift 3核心数据删除对象

时间:2016-06-24 15:54:03

标签: ios xcode core-data swift3

不幸的是,新的核心数据语义让我发疯。我之前的问题有一个干净的代码,由于头文件的自动生成不正确而无效。现在我继续我的工作删除对象。 我的代码似乎很简单:

func deleteProfile(withID: Int) {
    let fetchRequest: NSFetchRequest<Profile> = Profile.fetchRequest()
    fetchRequest.predicate = Predicate.init(format: "profileID==\(withID)")
    let object = try! context.fetch(fetchRequest)
    context.delete(object)
} 

我使用print(object)代替context.delete(object)进行了“硬”调试,它向我展示了正确的对象。 所以我只需删除它。

P.S。没有deleteObject。现在NSManagedContext只有public func delete(_ sender: AnyObject?)

8 个答案:

答案 0 :(得分:68)

在您的情况下,获取的结果是托管对象的数组 [Event],因此您可以枚举数组并删除所有匹配的对象。 示例(使用try?代替try!以避免案例发生崩溃 获取错误):

if let result = try? context.fetch(fetchRequest) {
    for object in result {
        context.delete(object)
    }
}

如果不存在匹配的对象,则获取成功,但结果为 数组是空的。

注意:在您的代码中,object的类型为[Event],因此在

context.delete(object)

编译器创建对

的调用
public func delete(_ sender: AnyObject?)

NSObject的方法,而不是预期的

public func delete(_ object: NSManagedObject)

NSManagedObjectContext的方法。这就是你的代码编译的原因 但在运行时失败。

答案 1 :(得分:40)

这里的技巧是删除对象后保存上下文。

let fetchRequest: NSFetchRequest<Profile> = Profile.fetchRequest()
fetchRequest.predicate = Predicate.init(format: "profileID==\(withID)")
let objects = try! context.fetch(fetchRequest)
for obj in objects {
    context.delete(obj)
}

do {
    try context.save() // <- remember to put this :)
} catch {
    // Do something... fatalerror
}

我希望这可以帮助别人。

答案 2 :(得分:18)

删除核心数据对象swift 3

// MARK: Delete Data Records

func deleteRecords() -> Void {
    let moc = getContext()
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")

     let result = try? moc.fetch(fetchRequest)
        let resultData = result as! [Person]

        for object in resultData {
            moc.delete(object)
        }

        do {
            try moc.save()
            print("saved!")
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        } catch {

        }

}

// MARK: Get Context

func getContext () -> NSManagedObjectContext {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    return appDelegate.persistentContainer.viewContext
} 

答案 3 :(得分:9)

func deleteRecords() {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext

    let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "nameofentity")
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)

    do {
        try context.execute(deleteRequest)
        try context.save()
    } catch {
        print ("There was an error")
    }
}

答案 4 :(得分:3)

Swift 4.1&amp; 4.2

     let appDelegate = UIApplication.shared.delegate as! AppDelegate
     let context = appDelegate.persistentContainer.viewContext
     let requestDel = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
     requestDel.returnsObjectsAsFaults = false
  // If you want to delete data on basis of some condition then you can use NSPredicate
  //  let predicateDel = NSPredicate(format: "age > %d", argumentArray: [10])
  // requestDel.predicate = predicateDel


     do {
          let arrUsrObj = try context.fetch(requestDel)
          for usrObj in arrUsrObj as! [NSManagedObject] { // Fetching Object
              context.delete(usrObj) // Deleting Object
         }
     } catch {
          print("Failed")
     }

    // Saving the Delete operation
     do {
         try context.save()
     } catch {
         print("Failed saving")
     }

答案 5 :(得分:2)

Swift 4,不使用实体字符串

let fetchRequest: NSFetchRequest<Profile> = Profile.fetchRequest()
fetchRequest.predicate = Predicate.init(format: "profileID==\(withID)")

do {
    let objects = try context.fetch(fetchRequest)
    for object in objects {
        context.delete(object)
    }
    try context.save()
} catch _ {
    // error handling
}

答案 6 :(得分:0)

从核心数据中删除对象

let entity = NSEntityDescription.entity(forEntityName: "Students", in: managedContext)
        let request = NSFetchRequest<NSFetchRequestResult>()
        request.entity = entity
        if let result = try? managedContext.fetch(request) {
            for object in result {
                managedContext.delete(object as! NSManagedObject)
            }
            txtName.text = ""
            txtPhone.text = ""
            txt_Address.text = ""
            labelStatus.text = "Deleted"

        }

答案 7 :(得分:0)

在Swift 5、4.2中删除带有查询的核心数据对象

let fetchrequest = NSFetchRequest<Your_Model>(entityName: "Your_Entity_Name")
fetchrequest.predicate = NSPredicate(format: "any your_key == %d", your_value)

希望这对某人有帮助