本文介绍了删除核心数据中的第一个对象(快速)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在请求Core Data根据contentid以升序返回我的Entity条目:

I am requesting Core Data to return me its Entity entries in ascending order based on contentid:

let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!

let sort = NSSortDescriptor(key:"contentid", ascending:true)
fetchRequest.sortDescriptors = [sort]

let fetchedResults = managedObjectContent.executeFetchRequest(fetchRequest, error: &error) as! [NSManagedObject]

如何删除Core Data返回的,升序的条目中的第一个对象?

How do I delete the first object in Core Data's returned, ascending entries?

我还尝试通过指定以下内容来获取单个对象:

I have also tried getting a single object by specifying:

fetchRequest.fetchLimit = 1

我认为这样做会返回[NSManagedObject],因此尝试执行以下操作:

Thinking that this would return an [NSManagedObject], I attempted to then perform:

managedObjectContext.deleteObject(fetchedResults)

但是它引发了错误:无法调用类型为'([NSManagedObject])'的方法deleteObject。我到底在做什么错?我是否需要将 [NSManagedObject] 转换为 NSManagedObject

But it threw the error: cannot invoke method deleteObject with type '([NSManagedObject])'. What exactly am I doing incorrectly? Do I need to convert [NSManagedObject] to NSManagedObject, perhaps?

推荐答案

尝试一下:

let fetchedResults = context.executeFetchRequest(fetchRequest, error: nil)
if let result = fetchedResults?.first as? NSManagedObject {
    context.deleteObject(result)
}

executeFetchRequest 返回 [AnyObject]?,因此您必须将其拆开,取出第一个对象并将其转换为 NSManagedObject 。之后,您将可以对该对象执行删除操作。

executeFetchRequest returns [AnyObject]? so you must unwrap it, take first object and cast it to NSManagedObject. After that you will be able to perform delete with this object.

这篇关于删除核心数据中的第一个对象(快速)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 01:28