People are asking what is the way to run task in an thread. One of the answer accepted by many people(from the link) is to use GCD.
So, I tried in this way by printing out thread id to see if the task is really executed in another thread after put into GCD queue:
// a function in MyService class
- (void) doTask {
NSLog(@"start do task on thread = %@", [NSThread currentThread]);
dispatch_queue_t queue = dispatch_queue_create("com.company.myqueue", DISPATCH_QUEUE_SERIAL);
dispatch_sync(queue, ^{
NSLog(@"execute task on thread = %@", [NSThread currentThread]);
});
}
I run :
// this is not main thread
[myService doTask]
The console output is this:
start do task on thread = <NSThread: 0x15b4be00>{number = 6, name = (null)}
execute task on thread = <NSThread: 0x15b4be00>{number = 6, name = (null)}
It looks like the task is NOT executed in another thread, it is on the same thread as the caller thread. Do I misunderstand something? Why GCD doesn't execute task in a separate thread but many pepole accept the answer in that link?