ios Swift 3 核心数据删除对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38017449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift 3 Core Data Delete Object
提问by Martin R
Unfortunately the new Core Data semantics make me crazy. My previous question had a clean code that didn't work because of incorrect auto generation of header files. Now I continue my work with deleting objects. My code seems to be very simple:
不幸的是,新的 Core Data 语义让我发疯了。我之前的问题有一个干净的代码,由于头文件的自动生成不正确而无法工作。现在我继续删除对象。我的代码似乎很简单:
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)
}
I did a "hard" debug with print(object)instead of context.delete(object)and it showed me the right object.
So I need just to delete it.
我用print(object)而不是进行了“硬”调试,context.delete(object)它向我展示了正确的对象。所以我只需要删除它。
P.S. there is no deleteObject. Now NSManagedContext has only public func delete(_ sender: AnyObject?)
PS没有deleteObject。现在 NSManagedContext 只有public func delete(_ sender: AnyObject?)
回答by Martin R
The result of a fetch is an arrayof managed objects, in your case
[Event], so you can enumerate the array and delete all matching objects.
Example (using try?instead of try!to avoid a crash in the case
of a fetch error):
获取的结果是一个托管对象数组,在您的情况下
[Event],因此您可以枚举该数组并删除所有匹配的对象。示例(使用try?而不是try!在获取错误的情况下避免崩溃):
if let result = try? context.fetch(fetchRequest) {
for object in result {
context.delete(object)
}
}
If no matching objects exist then the fetch succeeds, but the resulting array is empty.
如果不存在匹配的对象,则获取成功,但结果数组为空。
Note:In your code, objecthas the type [Event]and therefore in
注意:在您的代码中,object具有类型[Event],因此在
context.delete(object)
the compiler creates a call to the
编译器创建一个调用
public func delete(_ sender: AnyObject?)
method of NSObjectinstead of the expected
的方法NSObject而不是预期的
public func delete(_ object: NSManagedObject)
method of NSManagedObjectContext. That is why your code compiles
but fails at runtime.
的方法NSManagedObjectContext。这就是您的代码编译但在运行时失败的原因。
回答by J. Lopes
The trick here, it is save context after deleting your objects.
这里的技巧是在删除对象后保存上下文。
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
}
I hope this can help someone.
我希望这可以帮助某人。
回答by Raj Joshi
Delete core data objects swift 3
删除核心数据对象 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
}
回答by Hitesh Chauhan
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")
}
}
回答by Gurjinder Singh
Swift 4.1, 4.2 and 5.0
斯威夫特 4.1、4.2 和 5.0
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")
}
回答by Sonius
Swift 4 without using string for Entity
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
}
回答by Chanaka Caldera
Delete Core Data Object with query in Swift 5, 4.2
在 Swift 5、4.2 中使用查询删除核心数据对象
let fetchrequest = NSFetchRequest<Your_Model>(entityName: "Your_Entity_Name")
fetchrequest.predicate = NSPredicate(format: "any your_key == %d", your_value)
hope this will help to someone
希望这会对某人有所帮助
回答by CSE 1994
Delete the object from core data
从核心数据中删除对象
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"
}

