How to use variables by reference in a code block?
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;
dispa开发者_StackOverflowtch_async(queue, ^{
__block boolean hi2 = hi;
if (hi2 == YES)
do stuff;
});
And neither of those seem to work.
__block BOOL hi
should do what you want. Note that if you're dispatching asynchronously then there's a chance that the if (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.
I'm no expert on blocks so I don't know if there's a way to not capture the value of a primitive variable inside of one (but I think there isn't). The solutions that would leap to mind though are to use a pointer or an NSNumber to resolve the issue.
Pointer
/* this obviously needs to still be around to be dereferenced when the block executes */
BOOL hi = YES;
BOOL* hiPtr = &hi;
dispatch_async(queue, ^{
if (*hiPtr == YES)
do stuff;
});
NSNumber
/* this obviously needs to still be around to be dereferenced when the block executes */
__block NSNumber* hi = [NSNumber numberWithBool: YES];
dispatch_async(queue, ^{
if ([hi boolValue] == YES)
do stuff;
});
精彩评论