问题
I am building a social media app where multiple users can edit the same CloudKit record at the same time. Should I implement a locking mechanism so that only one user can edit at a time (these edits may conflict with each other), or does CloudKit have a handy built-in way for dealing with this?
If I implement a locking mechanism, my plan would be to add a binary attribute to the editable records--this attribute would have a value of 1 if someone else is editing, and 0 if no one is currently editing. Does this sound like a reasonable way to do this?
回答1:
Cloudkit has a mechanism for managing this called the change token. It's similar to a timestamp that's updated each time a record is changed. When you try to write, the last change token you have is passed to the server along with your new data. You can set policies that says how the server should handle collisions, such as the last writer always overwrites. Or that the last writer is rejected.
In the latter case, the second writer will receive a NSError. Embedded in the userInfo of that error are three versions of the record: the current on one the server, the version you tried to submit, and the common ancestor. This allows you compare the differences, merge the data as appropriate and re-save. Or you can re-fetch the record (which will update your version of the change token), and then save again.
I would recommend watching the WWDC cloudkit videos. I believe WWDC session 2014 session 231, "Advanced Cloudkit," and WWDC 2015 session 715 "Cloudkit Tips and Tricks," have the most helpful info.
来源:https://stackoverflow.com/questions/43816502/multiple-users-editing-same-cloudkit-record