【问题标题】:How to set the type of NSBatchDeleteResult of a NSBatchDeleteRequest?如何设置 NSBatchDeleteRequest 的 NSBatchDeleteResult 类型?
【发布时间】:2017-07-16 11:11:52
【问题描述】:

我有一些执行批量删除请求的核心:

extension NSManagedObject: Clearable {
    /// Clears all objects of this type in coreData
    static func clearAll() {
        let context = AppDelegate.sharedInstance()?.coreDataHelper.objectContext()
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing:self))
        let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do {
            if let unwrappedContext = context {
                unwrappedContext.shouldDeleteInaccessibleFaults = true
                let result = try unwrappedContext.execute(batchDeleteRequest) as? NSBatchDeleteResult
                DLog("result \(result.debugDescription)")
                switch result!.resultType {
                case .resultTypeCount:
                    DLog("resultTypeCount")
                case .resultTypeObjectIDs:
                    DLog("resultTypeObjectIDs")
                case .resultTypeStatusOnly:
                    DLog("resultTypeStatusOnly")
                }
                if let objectIDArray = result?.result as? [NSManagedObjectID] {
                    let changes = [NSDeletedObjectsKey : objectIDArray]
                    NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [unwrappedContext])
                }
                try context?.save()
            }
        } catch let error as NSError {
            DLog("Error removing : \(error), \(error.localizedDescription)")
        }
    }
}

代码运行正常,但是批量删除的结果总是.resultTypeStatusOnly

https://developer.apple.com/library/content/featuredarticles/CoreData_Batch_Guide/BatchDeletes/BatchDeletes.html#//apple_ref/doc/uid/TP40016086-CH3-SW2 此处的文档在标题下说 在执行后更新您的应用程序

通知应用程序中的对象很重要 内存已过时,需要刷新。

为此,结果类型必须为.resultTypeObjectIDs,才能触发NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [unwrappedContext]) 部分。只是不清楚你是如何得到的。

如何设置结果的类型?

【问题讨论】:

    标签: ios swift core-data


    【解决方案1】:

    您可以在batchDeleteRequest 上设置resultType 属性。所以,同样来自https://developer.apple.com/library/content/featuredarticles/CoreData_Batch_Guide/BatchDeletes/BatchDeletes.html

    executeRequest 成功完成后,会收到响应。该响应可以采取两种形式之一。通过在 NSBatchDeleteRequest 上设置 resultType 属性来确定响应的形式。默认值为 NSStatusOnlyResultType,它不返回任何内容。 另一个选项是 NSBatchDeleteObjectIDsResultType,它返回一个 NSManagedObjectID 实例数组,指示在执行期间删除了哪些实体。

    希望这会有所帮助。祝你好运!

    【讨论】:

    • 正确的语法是:batchDeleteRequest.resultType = .resultTypeObjectIDs
    猜你喜欢
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 2021-12-01
    • 2011-12-12
    • 1970-01-01
    相关资源
    最近更新 更多