Apple Blocks vs C ++ 11 Lambdas
I was playing around with C ++ 11 and Apple blocks and I tried to create a kind of mediator function. Code:
#include <functional>
#include <stdio.h>
void range(int low, int high, int& ref, std::function<void(void)> block){
int a = low;
while(a < high){
ref = a;
block();
a++;
}
}
void range(int low, int high, int& ref, void (^block)(void)){
int a = low;
while(a < high){
ref = a;
block();
a++;
}
}
int main(){
int a = 0;
range(0, 5, a, [&](){
printf("%i\n", a);
});
int b = 0;
range(0, 5, b, ^(){
printf("%i\n", b);
});
}
The first one, using C ++ 11 Lambdas worked as I expected and gives the following output
0 1 2 3 4
The second, using the Apple Blocks API, gives 5 zeros, is there a way to make it work for blocks as well?
source to share
Direct link to the source :
Only the value will be captured unless you specify otherwise. This means that if you change the external value of a variable between the time you defined the block and the time it was called, the value captured by the block does not change.
The captured value is the copy int b
that has the initial value 0
.
Then they go on to indicate:
If you need to change the value of a captured variable from within a block, you can use the __block store type modifier in the original variable declaration.
And they provide the following code example:
__block int anInteger = 42;
void (^testBlock)(void) = ^{
NSLog(@"Integer is: %i", anInteger);
};
anInteger = 84;
testBlock(); // Prints "Integer is: 84"
I advise you to stick with Lambda.
source to share