0

CKDatabase save(_:completionHandler:) has a box that says the following below. Yet when I run the method, the completionHandler runs after the print statement after the call to the save method. I noticed the declaration of the method to be run synchronously has an escaping completionHandler. If the method is run synchronously, doesn't using an escaping completionHandler defeat the purpose of executing the method synchronously, or is the documentation wrong and the method is actually run asynchronously both ways?

Concurrency Note

You can call this method from synchronous code using a completion handler, as shown on this page, or you can call it as an asynchronous method that has the following declaration:

func save(_ record: CKRecord) async throws -> CKRecord

For information about concurrency and asynchronous code in Swift, see Calling Objective-C APIs Asynchronously.

Here is my essential code with the nonessentials taken out:

print("*** 1 before self.privateCloudKitDatabase.save(record)")

self.privateCloudKitDatabase.save(record) {
   
  recordReturned, errorReturned in
   
  print("*** 2 closure self.privateCloudKitDatabase.save(record)")
   
}

print("*** 3 after self.privateCloudKitDatabase.save(record)")

Here's the debug window:

*** 1 before self.privateCloudKitDatabase.save(record)

*** 3 after self.privateCloudKitDatabase.save(record)

. . . (other print statements)

*** 2 closure self.privateCloudKitDatabase.save(record)

daniel
  • 1,446
  • 3
  • 29
  • 65
  • 2
    The quoted text never says that this function is synchronous. It says you **can call it from synchronous code**. – burnsi Oct 15 '22 at 07:48
  • As you noted the completion handler being `@escaping` wouldn't make sense if the completion handler would not escape the scope of the function because in that case the closure's arguments could just be returned from the function. – fruitcoder Oct 17 '22 at 08:52
  • So either of the two ways I call the method would be asynchronous? Why then would Apple give me two options? What difference would it make to choose one option or the other? – daniel Oct 17 '22 at 10:58
  • 1
    You mean async / await or closure? That are two different ways to achieve the same. The difference is structural. – burnsi Oct 17 '22 at 11:30
  • @burnsi yes. Aren’t both of those asynchronous? – daniel Oct 18 '22 at 22:04
  • @burnsi I just looked up async await. I’ll think about it another time. Thanks for the comments. – daniel Oct 18 '22 at 22:13

0 Answers0