netshark1000
netshark1000

Reputation: 7403

swift: Grand-Central-Dispatch but code is executed on mainthread?

Im importing data with an adressbookframework and storing the contacts within core data. The method is wrapped in GCD but the UI doesn't respond and all the code is executed on thread 1. What's wrong with my code?

func importContacts(){

    dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.value), 0)) {

            self.importContactsFromAdressbook() 
        }
}

Upvotes: 1

Views: 98

Answers (1)

Renfei Song
Renfei Song

Reputation: 2960

Firstly, you are using dispatch_get_global_queue and designating QOS_CLASS_BACKGROUND as your operation queue. This will result in your block to be executed in the thread for the background tasks, which is not the main thread.

The method is wrapped in GCD but the UI doesn't respond...

If I understand you correctly, you are attempting to update the UI in the block. This is not allowed. The Cocoa UI frameworks (including the UIKit and AppKit) are not thread-safe. Any update/interaction of UI elements must be done on the main thread.

So, if your importContactsFromAdressbook is concerning the UI, you should use dispatch_get_main_queue to send it to the main thread instead.

Might be useful: Concurrency Programming Guide

Upvotes: 3

Related Questions