Can fetchAll invoked in background Thread? #277

Closed
opened 2025-12-29 15:28:07 +01:00 by adam · 2 comments
Owner

Originally created by @CoderCMY on GitHub (Jul 15, 2019).

I query a table like this, and I got the result succeed at first ,when i call the tableView's reloadData method , I found all the book's properties is nil in "cellForRowAt" method, I'm so
confused ,who konws why???

func getAllBooks(completion: @escaping (_ books: [Book]?) -> Void) {
        var books: [Book]?
        CoreStore.perform(asynchronous: { (transaction) -> Void in
            books = transaction.fetchAll(From<Book>().orderBy(.descending(\.updateTime)))
        }) { (result) in
            switch result {
            case .success:
                completion(books)
            case .failure:
                completion(books)
            }
        }
    }
Originally created by @CoderCMY on GitHub (Jul 15, 2019). I query a table like this, and I got the result succeed at first ,when i call the tableView's reloadData method , I found all the book's properties is nil in "cellForRowAt" method, I'm so confused ,who konws why??? ```swift func getAllBooks(completion: @escaping (_ books: [Book]?) -> Void) { var books: [Book]? CoreStore.perform(asynchronous: { (transaction) -> Void in books = transaction.fetchAll(From<Book>().orderBy(.descending(\.updateTime))) }) { (result) in switch result { case .success: completion(books) case .failure: completion(books) } } } ```
adam added the question label 2025-12-29 15:28:07 +01:00
adam closed this issue 2025-12-29 15:28:07 +01:00
Author
Owner

@JohnEstropia commented on GitHub (Jul 18, 2019):

You will need to convert your books to main thread instances before you use them:

func getAllBooks(completion: @escaping (_ books: [Book]?) -> Void) {
        CoreStore.perform(asynchronous: { (transaction) -> [Book] in
            return transaction.fetchAll(From<Book>().orderBy(.descending(\.updateTime)))
        }) { (books) in
            completion(CoreStore.fetchExisting(books))
        }
    }
@JohnEstropia commented on GitHub (Jul 18, 2019): You will need to convert your `books` to main thread instances before you use them: ``` func getAllBooks(completion: @escaping (_ books: [Book]?) -> Void) { CoreStore.perform(asynchronous: { (transaction) -> [Book] in return transaction.fetchAll(From<Book>().orderBy(.descending(\.updateTime))) }) { (books) in completion(CoreStore.fetchExisting(books)) } } ```
Author
Owner

@CoderCMY commented on GitHub (Jul 18, 2019):

I've solved this problem with your method, Thank you very much

@CoderCMY commented on GitHub (Jul 18, 2019): I've solved this problem with your method, Thank you very much
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/CoreStore#277