使用func删除二进制核心数据



我想删除核心数据二进制数据集中的特定项。我已经在下面添加了我的所有代码。我试图按照我所做的来保存有效的数据,但试图将其应用于删除目前不起作用。不知道如何着手解决这个问题。我在helper类的上下文删除时遇到运行时错误。

基本类

func deleteImage(imageNo:Int) {
// first check the array bounds
let info = DataBaseHelper.shareInstance.fetchImage()
if info.count > imageNo {
// check if the data is available
if let imageData = info[imageNo].img {
DataBaseHelper.shareInstance.deleteImage(data: imageData)

} else {
// no data
print("data is empty")
}
} else {
// image number is greater than array bounds
print("you are asking out of bounds")
}
}
override func viewDidLoad() {
super.viewDidLoad()
deleteImage(imageNo: 2)}

辅助类

class DataBaseHelper {
static let shareInstance = DataBaseHelper()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

func deleteImage(data: Data) {
let imageInstance = Info(context: context)
imageInstance.img = data

do {
try context.delete(data)
print("Image is saved")
} catch {
print(error.localizedDescription)
}
}}

错误

你上面做错的是

func deleteImage(data: Data) { 
// here you create a new object with context 
let imageInstance = Info(context: context) 
// assigning data to object img property 
imageInstance.img = data

// deleting the unsaved object which cause error 
do {
try context.delete(data)
print("Image is saved")
} catch {
// this part will be execute because object is not saved
print(error.localizedDescription)
}
}

所以事情很清楚,首先你应该保存对象来删除它,否则会导致错误。

那么如何删除特定对象

class DataBaseHelper {
static let shareInstance = DataBaseHelper()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

// pass the object in parameter it will delete the specific info object from CoreData that you will provide in argument
func deleteInfo(info: Info) {
do {
try context.delete(info)
print("Image is saved")
} catch {
print(error.localizedDescription)
}
}
// if you want to remove image but not the info row/object just assign it nil and save again 
func deleteImage(info: Info) {
info.img = nil
do {
try context.save()
print("Image is removed but info still here")
} catch {
print(error.localizedDescription)
}
}
}

这就是删除图像的方法

if let info = info[imageNo]{
DataBaseHelper.shareInstance.deleteImage(info: info)

}

最新更新