参考 https://blog.csdn.net/Deft_MKJing/article/details/53165799
int a = 1;
// 这里的^{}初始化的block赋值给block变量,在OC中没有具体写明的情况下应该就是strong类型的,这就是上面第三点的例子
// 打印出来 first <__NSMallocBlock__: 0x60800004d290>
void (^block)(void) = ^{
NSLog(@"%d",a);
};
NSLog(@"first %@",block);
// 没有截获变量的时候就是globalBlock
// second<__NSGlobalBlock__: 0x102f80100>
NSLog(@"second%@",^{NSLog(@"呵呵");});
// 截获了变量就是stackBlock
// third<__NSStackBlock__: 0x7fff5cc7faa0>
NSLog(@"third%@",^{NSLog(@"%d",a);});
__block int val = 10;
__strong blk strongPointerBlock = ^{NSLog(@"val1 = %d", ++val);};
// strongPointerBlock: <__NSMallocBlock__: 0x600000044e90>
NSLog(@"strongPointerBlock: %@", strongPointerBlock); //1
__weak blk weakPointerBlock = ^{NSLog(@"val2 = %d", ++val);};
// weakPointerBlock: <__NSStackBlock__: 0x7fff5282ea70>
NSLog(@"weakPointerBlock: %@", weakPointerBlock); //2
// mallocBlock3: <__NSMallocBlock__: 0x608000046930>
NSLog(@"mallocBlock3: %@", [weakPointerBlock copy]); //3
// 截获了test <__NSStackBlock__: 0x7fff5282ea48>
NSLog(@"test4 %@", ^{NSLog(@"val4 = %d", ++val);}); //4
// test5 <__NSMallocBlock__: 0x60800005c0b0>
NSLog(@"test5 %@", [^{NSLog(@"val4 = %d", ++val);} copy]); //5
// stackBlock经过传参 打印
NSLog(@"传参后 %@",[self getBlock]);
}
- (blk)getBlock
{
int val = 11;
// 上面已经介绍了,这种直接打印传参前的block,应该是__NSStackBlock__
NSLog(@"传参前:%@",^{NSLog(@"%d",val);});
// 那么现在我们直接传出去
return ^{NSLog(@"%d",val);};
}
网友评论