问题
I need to save changes not only locally into Core Data
, but on server too.
My concern is, in my case user can do bunch of interaction in a short time. Between interaction there is not enough time to receive success message returned from server. So either I lock the GUI, until next message returns - this is the case now -, or choose a different approach.
My new approach would be to let user do many interactions and put transactions onto undo stack
provided by NSUndoManager
, enabled on NSManagedObjectContext
, BUT save / commit ONLY that transaction for which success message was received. How can I move undo "cursor" one at a time, commit records one by one, although context contains already planty of unsaved changes?
回答1:
NSUndoManager
is not really suited to this task. You can tell it to undo or redo actions, but you can't inspect those actions or selectively save data in the current undo stack.
What I've done in the past is create my own queue of outgoing changes. Whenever changes are saved locally, add those changes to a list of un-synced outgoing changes. Then use a different queue to handle processing that queue by sending them to the server and, if the server reports success, clearing out those changes. You can use NSManagedObjectContextWillSaveNotification
and/or NSManagedObjectContextDidSaveNotification
to monitor changes and update the outbound queue.
This means that the iOS device may have queued changes that the server doesn't know about, especially if the network is unreliable or unavailable. That's pretty much unavoidable in those situations though, unless you do something awful like refuse to let people make new changes until the network comes back up.
来源:https://stackoverflow.com/questions/30518146/save-nsundomanager-transactions-one-by-one