Swift 3核心数据删除对象 [英] Swift 3 Core Data Delete Object

查看:228
本文介绍了Swift 3核心数据删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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)进行了硬调试,它显示了我正确的对象。
所以我只需删除它。

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.

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

P.S. there is no deleteObject. Now NSManagedContext has only public func delete(_ sender: AnyObject?)

推荐答案

fetch的结果是托管对象的数组,在你的情况下是
[Event] ,所以你可以枚举数组并删除所有匹配的对象。
示例(使用尝试?而不是尝试!以避免在
的情况下发生崩溃获取错误):

The result of a fetch is an array of 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):

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.

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

Note: In your code, object has the type [Event] and therefore in

context.delete(object)

编译器创建对

public func delete(_ sender: AnyObject?)

的方法NSObject 而不是预期的

public func delete(_ object: NSManagedObject)

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

method of NSManagedObjectContext. That is why your code compiles but fails at runtime.

这篇关于Swift 3核心数据删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆