在MRC环境下: this
block对局部变量的影响:spa
使用局部变量:a到block块中,为了在block中可以使用这个变量,将a拷贝放到常量区 域 code
int a = 10; orm
若是访问局部对象,为了在block中可以使用这个对象,引用计数值加一对象
若是使用__block修饰,计数值则不加一it
__block NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"张三",@"李四",@"王五", nil]; //1 [button addTapBlcok:^(UIButton *button){ // a = 90; NSString *str = [array objectAtIndex:2]; NSLog(@"str:%@",str); }]; [array release];
block对全局变量的影响table
block在访问全局变量、方法的时候,会将这个变量对应的对象计数值加一class
block -> self -> self.view -> button -> block test
解决方式:使用__block修饰self 变量
总结:在MRC环境中__block的做用:(1)能够在block中修改变量值 (2)block内部访问属性的时候,能够使用__block修饰,避免计数值加一(解决循环引用问题)
MyButton *button = [MyButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(90, 90, 90, 90); button.backgroundColor = [UIColor redColor]; [self.view addSubview:button]; __block SecondViewController *this = self; [button addTapBlcok:^(UIButton *button){ // this->_index = 20; // NSLog(@"%ld",this->_index); [this test]; }]; } - (void)test { NSLog(@"test"); }
在ARC环境下:
__block:(1)可让局部变量在block中修改数据
//在ARC环境中 //__block:(1)可让局部变量在block中修改数据 __block int a = 9; [button addTapBlcok:^(UIButton *button){ a = 2; NSLog(@"a:%d",a); }];
解决循环引用问题
使用__weak修饰self
//在ARC环境中的解决方法: // strong weak __weak SecondViewController *weakThis = self; [button addTapBlcok:^(UIButton *button){ //在调用方法的时候,解决了循环引用问题 // [weakThis test]; //weakThis没法访问当前的属性 __strong SecondViewController *strongThis = weakThis; strongThis->_index = 20; NSLog(@"%ld",strongThis->_index); [strongThis test]; }]; } - (void)test { NSLog(@"test"); }