在MRC环境下:
block对局部变量的影响:
使用局部变量:a到block块中,为了在block中能够使用这个变量,将a拷贝放到常量区 域
int a = 10;
如果访问局部对象,为了在block中能够使用这个对象,引用计数值加一
如果使用__block修饰,计数值则不加一
__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对全局变量的影响
block在访问全局变量、方法的时候,会将这个变量对应的对象计数值加一
block -> self -> self.view -> button -> block
解决方式:使用__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");
}