iOS Block详解
iOS中Block实现原理的全面分析
在block内部可以访问block外部的变量,但这是一个新的内存空间变量
- (void)test {int m = 10;NSLog(@\"m-->%p\", &m); //m-->0x7ffee666c16cvoid (^myBlock)(void) = ^() {NSLog(@\"block m-->%p\", &m); //block m-->0x600002695370NSLog(@\"block m-->%d\", m); //block m-->10};myBlock();}
block内部也可以定义和block外部的同名的变量(就近原则)
- (void)test1 {int m = 10;NSLog(@\"m-->%p\", &m); //m-->0x7ffee666ccccvoid (^myBlock)(void) = ^() {int m = 100;NSLog(@\"block m-->%p\", &m); //block m-->0x7ffee666cc9cNSLog(@\"block m-->%d\", m); //block m-->100};myBlock();}
block内部不能直接修改外部变量,编译会报错
- (void)test2 {int m = 10;NSLog(@\"up m-->%p\", &m);void (^myBlock)(void) = ^() {m = 20; //报错NSLog(@\"block m-->%p\", &m);NSLog(@\"block m-->%d\", m);};myBlock();}
给局部变量加上__block关键字,则这个局部变量可以在block内部进行修改,block 是复制其引用地址来实现访问的
- (void)test3 {__block int m = 10;NSLog(@\"m-->%p\", &m); //m-->0x7ffeed1911a8void (^myBlock)(void) = ^() {m = 20;NSLog(@\"block m-->%p\", &m); //block m-->0x60000140c918NSLog(@\"block m-->%d\", m); //block m-->20};myBlock();}
block外部修改局部变量, block内部值不会改变
- (void)test4 {int m = 10;NSLog(@\"up m-->%p\", &m); //up m-->0x7ffee9fed1acvoid (^myBlock)(void) = ^() {NSLog(@\"block m-->%p\", &m); //block m-->0x60000267d670NSLog(@\"block m-->%d\", m); //block m-->10};m = 20;NSLog(@\"down m-->%p\", &m); //down m-->0x7ffee9fed1acmyBlock();}
静态变量和全局变量在加和不加__block都会直接引用变量地址。也就意味着可以修改变量的值
//全局变量NSString *name = @\"Sky\";- (void)test5 {NSLog(@\"up name-->%p\", &name); //up name-->0x100ca57d0void (^myBlock)(void) = ^() {name = @\"Tom\";NSLog(@\"block name-->%p\", &name); //block name-->0x100ca57d0NSLog(@\"block name-->%@\", name); //block name-->Tom};myBlock();dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{NSLog(@\"down name-->%p\", &name); //down name-->0x100ca57d0});}//静态变量- (void)test6 {static NSString *str = @\"abc\";NSLog(@\"up str-->%p\", &str); //up str-->0x1024597d8void (^myBlock)(void) = ^() {str = @\"zxc\";NSLog(@\"block str-->%p\", &str); //block str-->0x1024597d8NSLog(@\"block str-->%@\", str); //block str-->zxc};myBlock();dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{NSLog(@\"down str-->%p\", &str); //down str-->0x1024597d8});}
- 点赞1
- 收藏
- 分享
- 文章举报
春风酿酒发布了12 篇原创文章 · 获赞 12 · 访问量 206私信关注