NSBatchDeleteRequest导致合并冲突

时间:2017-09-21 16:50:16

标签: ios swift core-data swift4 xcode9

我有一个应用程序,它将与服务器同步,每天都可以更改数据。在同步期间,我删除了某些实体的所有数据,并使用新数据重新加载它。我使用以下代码:

    func SyncronizeUserComments(theData : [[AnyHashable : Any]])
{
    // Delete User Comments for this User and Connection
    let commentRequest : NSFetchRequest<NSFetchRequestResult> = PT_UserComments.fetchRequest()
    commentRequest.predicate = NSPredicate(format: "connection = %@ AND user == %@", Global_CurrentConnection!, Global_CurrentUser!)
    coreData.processDeleteRequest(request: commentRequest)

    // ADD the Comments to CoreData
    for index in 0..<theData.count {
        let result : [AnyHashable : Any] = theData[index]
        if let commentID = result["Comment_ID"] as? String, let commentText = result["Comment_Text"] as? String, let commentTitle = result["Comment_Title"] as? String
        {
            let newUserComment = PT_UserComments(context: coreData.persistentContainer.viewContext)
            newUserComment.connection = Global_CurrentConnection
            newUserComment.user = Global_CurrentUser
            newUserComment.comment_ID = commentID
            newUserComment.comment_Text = commentText
            newUserComment.comment_Title = commentTitle
        }
    }

    // Add the User Comments
    print("Added New User Comments: \(theData.count)")
    coreData.saveContext()
}

    func processDeleteRequest(request : NSFetchRequest<NSFetchRequestResult>)
{
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: request)
    deleteRequest.resultType = .resultTypeObjectIDs

    do {
        let result = try coreData.persistentContainer.viewContext.execute(deleteRequest) as? NSBatchDeleteResult
        let objectIDArray = result?.result as? [NSManagedObjectID]
        let changes = [NSDeletedObjectsKey : objectIDArray]
        NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes as Any as! [AnyHashable : Any], into: [coreData.persistentContainer.viewContext])
    } catch  {
        fatalError("Fatal Error Deleting Data: \(error)")
    }

    coreData.saveContext()
}

当我调用coreData.saveContext()时,我将对已删除的数据进行合并冲突。

在阅读有关CoreData和NSBatchDeleteRequest的内容时,会在SQL LITE级别删除并绕过内存缓存。

我能够让这个工作的唯一方法是设置:

context.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy

这是正确的,还是我做错了什么?我还在Core Data Stack中的saveContext()中设置了这个合并策略。

1 个答案:

答案 0 :(得分:0)

我只是花了几个小时来调试相同的问题,希望这可以对某人有所帮助。

问题是NSManagedObjectContext.mergeChanges(fromRemoteContextSave:, into:)更新了受管对象上下文,但没有更新已删除对象关系的行缓存版本号以匹配数据库文件中的更新版本号(Z_OPT),从而导致保存时不匹配。

如果您使用NSErrorMergePolicyType,则将导致下一次保存失败(或在关系被标记为保存时,将导致以后的保存失败),即使所有版本号都匹配。我没有在相关文档或WWDC视频中看到此消息,但我想Apple假设人们总是会选择非默认的合并策略。

因此,选择NSMergeByPropertyStoreTrumpMergePolicy可以解决问题,如问题中所述,但是您可能不希望对所有保存操作都使用此策略。为避免这种情况,我最终编写了仅解决版本不匹配的自定义合并策略。下面的代码(这是我最初在Obj-C中编写的未经测试的Swift,但应该等效):


//Configure the merge as below before saving
context.mergePolicy = AllowVersionMismatchMergePolicy(merge: .errorMergePolicyType)

//...

//The custom merge policy
class AllowVersionMismatchMergePolicy: NSMergePolicy {
    override func resolve(optimisticLockingConflicts list: [NSMergeConflict]) throws {
        do {
            //if the default resolve worked leave it alone
            return try super.resolve(optimisticLockingConflicts: list)
        } catch {
            //if any of the conflict is not a simple version mismatch (all other keys being equal), fail
            let hasValueConflict = list.contains { conflict -> Bool in
                //compare object and row cache
                if let objectSnapshot = conflict.objectSnapshot as NSObject?,
                    let cachedSnapshot = conflict.cachedSnapshot as NSObject? {
                    return !objectSnapshot.isEqual(cachedSnapshot)
                }
                //compare row cache and database
                if let cachedSnapshot = conflict.cachedSnapshot as NSObject?,
                    let persistedSnapshot = conflict.persistedSnapshot as NSObject? {
                    return !cachedSnapshot.isEqual(persistedSnapshot)
                }
                //never happens, see NSMergePolicy.h
                return true
            }
            if hasValueConflict {
                throw error
            }

            //Use store rollback merge policy to resolve all the version mismatches
            return try NSMergePolicy.rollback.resolve(optimisticLockingConflicts: list)
        }
    }
}