#import "ViewController.h"
@implementation ViewController
int tnt=1;
-(void)myMethod{
void(^blk)(void) = ^(void){
tnt = 3+1;
NSLog(@"tnt=>%d", tnt);
};
blk();
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self myMethod];
}
The variable tnt is outside but inside block its working perfectly fine. If i declare the tnt variable inside myMethod it start giving the __block required error.
In both case the tnt variable is outside of the block. Apple docs also says variable outside need __block storage type. Why its working when tnt is declared outside of myMethod.
I would guess that is related to scope. From the documentation:
When you put
int tnt=1;outside the lexical scope, I think you won’t have to use the__blockmodifier. And you have an example, here. You can also read the following:Since the
int tnt=1;is declared outside the lexical scope, it will survive the destruction of the stack.