//
// ViewController.m
// test_stack_block
//
// Created by jeffasd on 16/5/18.
// Copyright © 2016年 jeffasd. All rights reserved.
//
#import "ViewController.h"
typedef void(^TestBlock)(int);
@interface ViewController ()
//@property(nonatomic, copy) void (^)(int) block;
@property (nonatomic, copy)TestBlock testBlock;
@property (nonatomic, strong) void (^oneBlock)(int);
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
__block int inta = 2;
//weak类型的block不会进行 自动copy操作,但是此weak类型的block没有
//引用任何外部变量 会被立即转换成 NSGlobalBlock
__weak void (^ stackBlcok)(int) = ^(int var){
// inta = 3;
// NSLog(@"the var is %d", var);
// NSLog(@"the block inline is %@", stackBlcok);
};
NSLog(@"the block is %@", stackBlcok);
// stackBlcok(12);
NSLog(@"the block end is %@", stackBlcok);
//weak类型的block不会进行 自动copy操作,但是此weak类型的block没有
//引用任何外部变量 会被立即转换成 NSGlobalBlock
__weak void (^ weakstackBlcok)(int) = ^(int var){
NSLog(@"the inta is %d", var);//打印var变量不算引用外部变量,var变量是此block自己的变量
// NSLog(@"the inta is %d", inta);//引用外部变量inta 变量 由于所有类型的block创建时都是在stack中创建
};
NSLog(@"the weakstackBlcok is %@", weakstackBlcok);
// stackBlcok(12);
NSLog(@"the weakstackBlcok end is %@", weakstackBlcok);
// __weak void (^ weakBlcok)() = ^(){
//
//
//
// };
//
//
// NSLog(@"the weakBlcok is %@", weakBlcok);
// // stackBlcok(12);
// NSLog(@"the weakBlcok end is %@", weakBlcok);
__block void (^weakBlock)() = ^(){
NSLog(@"fsdfsdf");
return;
};
NSLog(@"the weak block is %@", weakBlock);
NSLog(@"test block type %@", ^{});
NSLog(@"test block type %@", ^{});
self.oneBlock = ^(int vara){
NSLog(@"the vara is %d", vara);
};
NSLog(@"the block is %@", self.oneBlock);
self.oneBlock(56);
NSLog(@"the block end is %@", self.oneBlock);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
int i = 10;
void (^block)() = ^{i;};
__weak void (^weakBlock)() = ^{i;};
void (^stackBlock)() = ^{};
__weak void (^weakstackBlock)() = ^{};
// ARC情况下
// 创建时,都会在栈中
// <__NSStackBlock__: 0x7fff5fbff730>
NSLog(@"1 %@", ^{i;});
//创建时如果没有引用外部变量,直接转换为__NSGlobalBlock__
NSLog(@"%@", ^{});
// 因为stackBlock为strong类型,且捕获了外部变量,所以赋值时,自动进行了copy
// <__NSMallocBlock__: 0x100206920>
NSLog(@"3 %@", block);
// 如果是weak类型的block,依然不会自动进行copy
// <__NSStackBlock__: 0x7fff5fbff728>
NSLog(@"4 %@", weakBlock);
// 如果block是strong类型,并且没有捕获外部变量,那么就会转换成__NSGlobalBlock__
// <__NSGlobalBlock__: 0x100001110>
NSLog(@"5 %@", stackBlock);
// 如果block是weak类型,并且没有捕获外部变量,那么也会转换成__NSGlobalBlock__
NSLog(@"6 %@", weakstackBlock);
// 在非ARC情况下,产生以下输出
// <__NSStackBlock__: 0x7fff5fbff6d0>
// <__NSStackBlock__: 0x7fff5fbff730>
// <__NSStackBlock__: 0x7fff5fbff700>
// <__NSGlobalBlock__: 0x1000010d0>
}
@end
自己对OC中Block的理解2
最新推荐文章于 2025-02-08 17:50:28 发布