gpt4 book ai didi

ios - Core Data 删除同名对象

转载 作者:行者123 更新时间:2023-11-28 11:22:14 24 4
gpt4 key购买 nike

//taken from Core Data    
var items:NSMutableArray = ["Item 1","Item 2","Item 1","Item 3"]

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if(editingStyle == .Delete){
let itemName = items.objectAtIndex(indexPath.row) as String
//delete all rows in core data with this item name
}
}

如何删除 Core Data 中字段名为“itemName”的所有行?

最佳答案

创建一个 NSFetchRequest 并使用您的项目名称设置一个 NSPredicate。执行此获取请求会为您提供一个包含所有具有该谓词的 NSManagedObjects 的数组。

然后遍历该数组并调用 NSManagedObjectContext 的方法 deleteObject(object)

let fetchRequest = NSFetchRequest(entityName: "yourEntityName")
fetchRequest.includesSubentities = false
fetchRequest.returnsObjectsAsFaults = false

fetchRequest.predicate = NSPredicate(format:"name == '\(itemName)'")

var error: NSError?

// moc is your NSManagedObjectContext here
items = moc.executeFetchRequest(fetchRequest, error: &error)!

for item in items {
moc.deleteObject(item)
}

关于ios - Core Data 删除同名对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26802408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com