How To Test In XCode That A Process Is Running On A Background Thread?

1.1k views Asked by At

I'm upgrading from AFNetworking 1.0 to AFNetworking 2.0. With AFNetworking 1.0 I could never get it to sync on a background thread so it was stalling my UI when it did sync.

I want to run all AFNetworking 2.0 syncs on a background thread and update the UI when the sync is happening but not stall the UI.

How can I test in XCode if AFNetworking is running on background thread? Is there a visual way to test which processes are running on which threads?

2

There are 2 answers

2
Michael Ochs On

First: A process is the one that contains multiple threads, so a process can never run on a background thread as it is the one that contains all the threads.

Now to your problem of communicating between threads: AFNetworking is build on top of NSOperation and NSOperationQueue. Each request is an operation running in an operation queue. This means every request is always running on a background queue, no matter where you started it. However, you can specify the queue on which your success and failure completion handler are called. If you do not specify a queue, your completion blocks are always called in the main queue.

So by default, your operations / connections are handled in the background to prevent your UI from blocking. Your completion handler however are called on the main thread, so that you are able to update your UI from there. If you use this default behaviour but your UI is still blocking, you might do to much work in the completion handler. In this case you should set a dedicated queue as for the completion handler. You can do so in every operation with -[AFURLConnectionOperation setCompletionQueue:].

Keep in mind that you need to dispatch all UIKit related calls to the main queue if you do so.

A side note: A background queue does not necessarily mean it is running in a background thread. Queues are implemented in grand central dispatch where the concept of threads does not exist. However, in general, the concept of gcd queues is pretty similar to threads, but you should try to not mix and match those two concepts in a single part of your application or thinks might get complicated and hard to debug.

0
bzz On

When you pause program execution, you can see all threads in the debug navigator. You can find detailed information about it in the iOS Developer Library.

debug navigator