您的位置:首页 > 移动开发 > IOS开发

IOS中的__block关键字简单使用

2015-05-13 20:16 375 查看
/**13.__block什么时候用?**/
结论:在block里面修改局部变量的值都要用__block修饰

/**14.请教一个问题:在block里面,
对数组执行添加操作,
这个数组需要声明成 __block吗?**/

不需要声明成__block,因为testArr数组的指针并没有变(往数组里面添加对象,指针是没变的,只是指针指向的内存里面的内容变了)

/**15.在block里面,
对NSInteger进行修改,
这个NSInteger是否需要声明成__blcok

?**/

NSInteger的值发生改变,则要求添加__block修饰

代码实例:

NSMutableArray *testArr =[[NSMutableArray alloc] initWithObjects:@"1",@"2", nil];
__block NSInteger a=10;
/**结论:在block里面修改局部变量的值都要用__block修饰**/
void (^TestBlock)(void) = ^{
//        NSMutableArray *temArr=[[NSMutableArray alloc] init];
//        testArr=temArr;//testArr数组的指针发生改变时,testArr要添加__block修饰

a=100;//a的值发生改变,则要求添加__block修饰
//        testArr不需要声明成__block,因为testArr数组的指针并没有变(往数组里面添加对象,指针是没变的,只是指针指向的内存里面的内容变了)
[testArr addObject:[NSString stringWithFormat:@"3"]];
NSLog(@"_block testArr :%@ a:%d", testArr,a);

};
a=0;
TestBlock();

NSLog(@"testArr :%@ a:%d", testArr,a);


运行结果:

2015-05-13 20:16:23.862 WXMovie_study[22827:1683307] _block testArr :(
1,
2,
3
) a:100
2015-05-13 20:16:23.862 WXMovie_study[22827:1683307] testArr :(
1,
2,
3
) a:100
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: