问题描述
不幸的是,新的 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.
附言没有 deleteObject
.现在 NSManagedContext 只有 public func delete(_ sender: AnyObject?)
P.S. there is no deleteObject
. Now NSManagedContext has only public func delete(_ sender: AnyObject?)
推荐答案
获取的结果是一个 array 托管对象,在您的情况下[Event]
,所以你可以枚举数组并删除所有匹配的对象.示例(使用 try?
而不是 try!
以避免崩溃获取错误):
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 caseof 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 resultingarray 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 compilesbut fails at runtime.
这篇关于Swift 3 核心数据删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!