重新认识Block

Block的本质

  • block本质上也是一个OC对象,它内部也有个isa指针
  • block是封装了函数调用以及函数调用环境的OC对象
  • block的底层结构如右图所示


    image.png

Block的类型

block有3种类型,可以通过调用class方法或者isa指针查看具体类型,最终都是继承自NSBlock类型

  • NSGlobalBlock ( _NSConcreteGlobalBlock )
  • NSStackBlock ( _NSConcreteStackBlock )
  • NSMallocBlock ( _NSConcreteMallocBlock )

image.png

image.png

ARC:2022-01-10 11:00:35.296362+0800 BlockTest[413:16792] 0 type globalBlock:NSGlobalBlock stackGlobal:NSMallocBlock mallocBlock:NSGlobalBlock
2022-01-10 11:00:35.296469+0800 BlockTest[413:16792] 1 type globalBlock:NSGlobalBlock stackGlobal:NSMallocBlock mallocBlock:NSMallocBlock
MRC:2022-01-10 11:06:08.031263+0800 BlockTest[428:18568] 0 type globalBlock:NSGlobalBlock stackGlobal:NSStackBlock mallocBlock:NSGlobalBlock
2022-01-10 11:06:08.031406+0800 BlockTest[428:18568] 1 type globalBlock:NSGlobalBlock stackGlobal:NSStackBlock mallocBlock:NSMallocBlock

Block的变量捕获

为了保证block内部能够正常访问外部的变量,block有个变量捕获机制


image.png

image.png

2022-01-10 14:15:19.730962+0800 BlockTest[474:45513] 0 staticGlobalValue:1, globalValue:2 staticValue:3 localValue:4
2022-01-10 14:15:19.730999+0800 BlockTest[474:45513] 1 staticGlobalValue:2, globalValue:3 staticValue:4 localValue:4


image.png

__block修饰符

__block可以用于解决block内部无法修改auto变量值的问题

__block不能修饰全局变量、静态变量(static)

编译器会将__block变量包装成一个对象


image.png

image.png

image.png

image.png

__block的__forwarding指针

image.png

image.png

image.png

image.png

你可能感兴趣的:(重新认识Block)