Block的類型
情況一(沒(méi)有捕獲任何變量)
MyBlock myBlock = ^{
};
NSLog(@"%@", [myBlock class]);
NSLog(@"%@", [[myBlock class] superclass]);
NSLog(@"%@", [[[myBlock class] superclass] superclass]);
NSLog(@"%@", [[[[myBlock class] superclass] superclass] superclass]);
2021-03-17 14:07:06.025933+0800 Block[40186:876779] __NSGlobalBlock__
2021-03-17 14:07:06.026095+0800 Block[40186:876779] __NSGlobalBlock
2021-03-17 14:07:06.026211+0800 Block[40186:876779] NSBlock
2021-03-17 14:07:06.026325+0800 Block[40186:876779] NSObject
情況二(捕獲局部變量)
- (void)test{
int a = 10;
static int b = 10;
MyBlock myBlock = ^{
NSLog(@"%d",a);//捕獲局部變量
NSLog(@"%@",self);//捕獲局部變量self
};
NSLog(@"%@", [myBlock class]);
NSLog(@"%@", [[myBlock class] superclass]);
NSLog(@"%@", [[[myBlock class] superclass] superclass]);
NSLog(@"%@", [[[[myBlock class] superclass] superclass] superclass]);
}
2021-03-17 14:09:53.836279+0800 Block[40238:879591] __NSMallocBlock__
2021-03-17 14:09:53.836436+0800 Block[40238:879591] __NSMallocBlock
2021-03-17 14:09:53.836553+0800 Block[40238:879591] NSBlock
2021-03-17 14:09:53.836657+0800 Block[40238:879591] NSObject
情況三()
int a_q = 10;
static int b_q = 10;
typedef void(^MyBlock)(void);
- (void)test{
int a = 10;
static int b = 10;
MyBlock myBlock = ^{
NSLog(@"%d",b);//捕獲局部靜態(tài)變量
NSLog(@"%d",a_q);//全局變量
NSLog(@"%d",b_q);//全局靜態(tài)變量
};
NSLog(@"%@", [myBlock class]);
NSLog(@"%@", [[myBlock class] superclass]);
NSLog(@"%@", [[[myBlock class] superclass] superclass]);
NSLog(@"%@", [[[[myBlock class] superclass] superclass] superclass]);
}
2021-03-17 14:14:58.449827+0800 Block[40366:886075] __NSGlobalBlock__
2021-03-17 14:14:58.449985+0800 Block[40366:886075] __NSGlobalBlock
2021-03-17 14:14:58.450110+0800 Block[40366:886075] NSBlock
2021-03-17 14:14:58.450222+0800 Block[40366:886075] NSObject
總結(jié):
block的最終的父類是NSObject, 說(shuō)明了Block的本質(zhì)是一個(gè)對(duì)象
Block的類型與內(nèi)存管理
根據(jù)Block在內(nèi)存中的位置分為三種類型NSGlobalBlock客燕,NSStackBlock, NSMallocBlock乎婿。
NSGlobalBlock:類似函數(shù),位于text段粹舵;(存放在數(shù)據(jù)區(qū))
NSStackBlock:位于棧內(nèi)存,函數(shù)返回后Block將無(wú)效;(存放在棧區(qū))
NSMallocBlock:位于堆內(nèi)存银亲。(存放在堆區(qū))
應(yīng)用程序的內(nèi)存分配:
程序區(qū)域 .text區(qū)(代碼段) 數(shù)據(jù)區(qū)域(.data區(qū))【一般存放全局變量】
堆區(qū)【alloc出來(lái)的對(duì)象 動(dòng)態(tài)分配內(nèi)存 需要程序員申請(qǐng)內(nèi)存 也需要程序員管理內(nèi)存】
棧區(qū)【存放局部變量 系統(tǒng)自動(dòng)分配內(nèi)存 自動(dòng)銷毀內(nèi)存】