I have a block that I submit to a queue and I only want the block to execute if a certain condition is true. It looks sort of like this:
bool hi = YES;
dispatch_async(queue, ^{
if (hi == YES)
do stuff;
});
The problem with this, is that if the value of hi changes to NO outside of the block after the block has been submitted to the queue but before it has been run, the value of hi inside of the block is still YES.
I looked through documentation and found the __block directive, which looks like it might help me, but hasn’t worked. I’ve tried:
__block bool hi = YES;
dispatch_async(queue, ^{
if (hi == YES)
do stuff;
});
and
bool hi = YES;
dispatch_async(queue, ^{
__block boolean hi2 = hi;
if (hi2 == YES)
do stuff;
});
And neither of those seem to work.
__block BOOL hishould do what you want. Note that if you’re dispatching asynchronously then there’s a chance that theif (hi == YES)is being run before you change hi to NO, even if the rest of the block isn’t. What you should really be doing is periodically checking hi to see if you should continue working, rather than checking once to see if you should start.