UIDocument autosave not working when calling updateChangeCount

人走茶凉 提交于 2019-12-23 03:45:28

问题


I have a custom subclass of UIDocument that I use to store the user's content for my app. I call -[UIDocument updateChangeCount:UIDocumentChangeDone] directly to track changes to the document. Saving and loading work fine, but the document never autosaves. Why would this be happening?


回答1:


It turns out that the problem was that I wasn't calling -[UIDocument updateChangeCount:] from the main thread. Despite the fact that UIDocument isn't a UI element, it is still part of UIKit and so the usual caveats about always interacting with UIKit classes from the main thread still applies.

Wrapping the code in a dispatch to the main queue fixed the issue:

dispatch_async(dispatch_get_main_queue(), ^{
    [doc updateChangeCount:UIDocumentChangeDone];
});



回答2:


First, an update on Jayson's answer for Swift:

DispatchQueue.main.async {
    doc.updateChangeCount(.done)
}

This works fine if you are just calling it in one or two places. However, if you have multiple calls, and a possibility of them being on background threads, then it may be beneficial to sub class UIDocument and override the updateChangeCount(:) function so that you enforce a main call. Otherwise, you become responsible for making the main call every time, which opens you up to a potential miss, leading to the document getting into the saveError state.

You would then have an override in your subclass like this:

override func updateChangeCount(_ change: UIDocumentChangeKind) {
    DispatchQueue.main.async {
        super.updateChangeCount(change)
    }
}


来源:https://stackoverflow.com/questions/26066569/uidocument-autosave-not-working-when-calling-updatechangecount

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!