Missing __block variable declaration for GCD?

Hello

Is missing or named fifferently __block variable definition which can be used in GCD block? Example:

// this code run in thread, so code do not block main UI
int res = 0;
dispatch_sync(dispatch_get_main_queue(), delegate()
{
  res = 1; // - error here, outer variable cannot be accessed in block
});
NSLog(res.stringValue);

It’s okay and correct, but in Objective-C res variable can be can be declared:

__block int res = 0;

and is accessible in block and outside (with value modified in block)

iOS reference: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Blocks/Articles/bxVariables.html

b.r.

in Elements, variables will always be captured as ion they were declared as __block, when they are accessed from within the block.

It will be nice, but problem is that they are not :slight_smile: Compiler says that variable is not accessible.

b.r.

Hm, weird. can you send us a full testcase? i use blocks pretty excessively, including captured vars. What’s the exact error you get? (even in ObjC, you can read locals, its just that with __blockany changes wont propagate out of the block.

Sorry it was a bit different case, so will precise is now.
If variable is as method ref variable, then it cannot be used that way. But this can by simple fixed by assign ref value to local variable and set result back after sync block. Like this:

public void superMethod(ref int mySuperVar)
{
	int temp = mySuperVar;
	dispatch_sync(dispatch_get_main_queue(), delegate()
	{
		temp++;
		NSLog(temp.stringValue);
	});
	mySuperVar = temp;
}

Anyway, do ref variable should be allowed in block or not?

blockcase.zip (116.1 KB)

b.r.

of course that wont do what you think it does.

“ref”/ “out” parameters are blocked from being used in an anonymous method because they would act unreliable. If the method that takes the anonymous and doesn’t block but executes the block later, what would happen to the value? What would the result be? When using a temp var like that it’s clear you know what you’re doing.

So all is clear :slight_smile: Thanks!

of course that wont do what you think it does.

Tested and it do :wink: It’s sync not async. Result is:
1
1
1

Check for commend at code. If You are sure that it should not be result as I’m thinking, then let me know before I’ll apply it in my code and after xx days will dig for weeks what happened :slight_smile:

public void superMethod(ref int mySuperVar)
{
    int temp = mySuperVar;
    dispatch_sync(dispatch_get_main_queue(), delegate()
    {
        temp++;
        NSLog(temp.stringValue);
    });
    mySuperVar = temp; // debugger show that temp = 0, nslog show 1
    NSLog(mySuperVar.stringValue);
}

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), delegate()
{
    int aa = 0;
    superMethod(ref aa);
    NSLog(aa.stringValue);
});

b.r.

Ah, yes. misread.