evermeer / EVCloudKitDao

Simplified access to Apple's CloudKit
Other
644 stars 67 forks source link

Which thread does completionHandler working in for query/save/connect? #95

Closed foolbear closed 6 years ago

foolbear commented 6 years ago

and query/save/connect must be invoke from main thread?

evermeer commented 6 years ago

queries are always performed on a background thread (default CloudKit behaviour). To make things easier the connect in EVCloudKitData will perform all callbacks on the main thread (since you probably often want to update the UI). For EVCloudKitDao all callbacks are still performed on a background thread.

foolbear commented 6 years ago

these are 2 questions:

  1. operations invoke
  2. operations completionHandler running in

about 3 operations:

  1. query
  2. saveItem??
  3. connect

for example:

// must be invoked in main thread?
func getOrNewBookFSForReadC(_ bookFS: BookFS, _ ckBook: CKBook, completion_: @escaping (CKBookFS?) -> Void) {
        EVCloudKitDao.publicDB.query(CKBookFS(), predicate: NSPredicate(format: "url == %@", bookFS.url), completionHandler: { results, _ in 
// in background thread 1
            var cKBookFS = CKBookFS()
            if results.count > 0 {
                cKBookFS = results[0]
                cKBookFS.readerCount += 1
            } else {
                cKBookFS.url = bookFS.url
                cKBookFS.imageUrl = bookFS.image_url
                cKBookFS.introduction = bookFS.introduction
                cKBookFS.readerCount = 1
                cKBookFS.putBook(ckBook.recordID.recordName)
            }

                        // it's ok invoked in background thread
            EVCloudData.publicDB.saveItem(cKBookFS, completionHandler: { cKBookFS in 
// in background thread 2 or main thread?
                completion_(cKBookFS)
            }, errorHandler: { error in
                completion_(nil)
                foolPrint("save CKBookFS error: \(error.localizedDescription)")
            })
            return false
        }, errorHandler: { error in
// main or background thread?
            completion_(nil)
            foolPrint("query CKBookFS error: \(error.localizedDescription)")
        })
    }
evermeer commented 6 years ago

Summarised this is how threading is handled:

foolbear commented 6 years ago

Thanks, it's clear.