简体   繁体   中英

Managing thread loop in objective-c

I take a look to the GCD , and coming from c++, it comes natural to write code in this way:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

   while(YES) {
     if(<condition>) {
       /* here I need to call a delegate */
     }
     sleep(1);
   }

});

Is this the right way to do a loop in a objective-c thread?

Trying to understand, I was looking inside Reachability framework that I suppose launch a background thread to continuously check connection status, but I can't understand how do the "loop".

Edit

Basically I have N objects saved on core data. When all this objects have setted its property "online" as YES, I need to launch a notification or delegate.

you can use timer for something like that recursive. or you can use recursive thread with delay interval. ARC behavior within a recursive block that can be helpfull.

I suppose it depends on what your code will be doing. It would be better to wait for something like an NSNotification rather than polling your condition, however if you have no other choice then that's fine.

It's really rare the need of creating a new persistent thread with a run loop in it.
If you need to create some operations in on a specific thread and those operations need to communicate with some other object using delegation, this would require a new persistent run loop.
For instance if you want to perform all NSURLConnection on a background thread, once you start the connection on a background thread since NSURLConnection is based on delegation, the thread will be closed right after reaching the end of that method and you will loose all the callbacks.
As I said it's really rare and also a bit complicated.
GCD concept is very different from thread, is GCD that decides to perform your block on a thread or another.
There are plenty of reachability version outside and as far as I remember none of them uses a particular thread, one uses a serial queue, but remember that queues and threads are really different concepts.
Back to you snippet I've never seen a block like that and I think is wrong, GCD will manage the existence of the thread and you don't need to create a run loop.
Maybe if you add more specification to your question I can be more helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM