我刚遇到一个奇怪的问题,那就是从Core Data中删除对象。 我的代码如下:
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Favorites")
fetchRequest.predicate = NSPredicate(format: "objectID == %ld", object.id)
do {
let favoriteObject = try context.fetch(fetchRequest) as! [Favorites]
if favoriteObject > 0 {
// Already exist. Delete
do {
context.delete(favoriteObject[0])
try context.save()
} catch let error as NSError {
print("Could not save. \(error.localizedDescription)")
}
}
我还要提到Favorites
与Objects
具有一对一的关系。执行完我的删除代码后,它使该关系无效,但记录仍保留在数据库列表中。真是奇怪出了什么问题,我该如何解决?
删除后,数据库中的记录如下:
`ObjectID` = `0`
`object`: `NULL`(the foreign key)
答案 0 :(得分:0)
假设您的谓词有效。 1)您正在获取'favoreteObject'数组,并尝试删除第一个数组... 2)尝试“如果favoirteObject.count> 0” 3)尝试从context中删除'do'框
if favoriteObject.count > 0 {
// Already exist. Delete
context.delete(favoriteObject[0])
do {
try context.save()
} catch let error as NSError {
print("Could not save. \(error.localizedDescription)")
}
}