如何获取获取请求以返回持久性存储中的对象数?

时间:2018-12-16 17:47:22

标签: core-data nsmanagedobject nsmanagedobjectcontext nspersistentstore

启动我的应用程序并创建第一个视图控制器时,还将创建一个新的后备NSManagedObject。此时,我还没有保存上下文(我从一个新的空持久存储开始)。

用户可以切换到另一个屏幕,如果没有保存的项目,则将显示一条消息;如果存在已保存的项目,则将显示项目列表。这是我检查已保存项目的方式:

func checkForSavedItems() -> Bool {
    var itemsDoExist = false
    let fetchRequest = NSFetchRequest<NSNumber>(entityName: "Items")
    fetchRequest.includesPendingChanges = false
    fetchRequest.resultType = .countResultType

    do {
        let countResult = try context.fetch(fetchRequest)
        itemsDoExist = countResult.first!.intValue > 0
    } catch let error {
        print(error)
    }
    return itemsDoExist
}

我希望fetchRequest.includesPendingChanges = false已确保不会保存尚未保存的新对象,而是将其计算在内。计数返回为1,因此它必须对NSManagedObjectContext

中的项目进行计数

这也表明获取请求正在返回上下文中的项目计数,而不是持久存储。

如何获取持久性存储中的实际项目数?

谢谢

1 个答案:

答案 0 :(得分:0)

我还希望fetchRequest.includesPendingChanges = false会排除已插入到上下文中但未保存到商店的对象。

但是,count(for: NSFetchRequest)方法应提供正确的计数。您可以找到Apple文档here