Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Atomic increment" with CloudKit

I want to implement a counter using CloudKit. Let's say I have a field called count of type Int(64). How can I go about implementing this counter so that multiple users can increment it at the same time?

If multiple users increment this counter at the same time, my CKModifyRecordsOperation might fail because of the conflict. I could take this failure and recursively try to save my record, but this doesn't work at scale.

In 2011, Parse launched a simple solution called atomic increment. You could write code like this and not worry about multiple users creating conflicting values: [gameScore incrementKey:@"score" byAmount:[NSNumber numberWithInt:10]. (That post here)

How can I do this with CloudKit?


1 Answers

I don't believe CloudKit has similar atomic increment functionality built in. But a similar effect can be achieved by setting savePolicy on the CKModifyRecordsOperation to ifServerRecordUnchanged and checking for a serverRecordChanged error (docs).

There is an existing answer here to a slightly different question: Increment field value in a CKRecord variable without fetching?

like image 105
bjtitus Avatar answered Sep 05 '25 06:09

bjtitus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!