1.Block的類型
全局Block(NSGlobalBlock)
void (^block)(void) = ^{
NSLog(@"------");
};
NSLog(@"%@",block);
//打印結(jié)果<__NSGlobalBlock__: 0x10bb2d030>
block 內(nèi)部沒有引用外部變量的 Block 類型都是 NSGlobalBlock 類型扒接,存儲(chǔ)于全局?jǐn)?shù)據(jù)區(qū),由系統(tǒng)管理其內(nèi)存羔沙,retain筹误、copy磺送、release操作都無效代虾。如果只引用全局變量和靜態(tài)變量也是全局Block歉摧。
堆Block(NSMallocBlock)
int a = 10;
void (^block)(void) = ^{
NSLog(@"----%d",a);
};
NSLog(@"%@",block);
打印結(jié)果
<__NSMallocBlock__: 0x60000179d950>
NSMallocBlock只需要對NSStackBlock進(jìn)行copy操作就可以獲取
棧Block(NSStackBlock)
之前我們通過
int a= 10;
NSLog(@"%@",^{
NSLog(@"----%d",a);
});
可以得出StackBlock艇肴,但是現(xiàn)在不行了,我們可以通過下面方式得出StackBlock
int a = 10;
void ( __weak ^block)(void) = ^{
NSLog(@"----%d",a);
};
// block_copy
NSLog(@"%@",block);
打印結(jié)果是
<__NSStackBlock__: 0x7ffeed6d53f8>
2.Block的循環(huán)引用和解決
循環(huán)引用
在ViewController聲明兩個(gè)屬性
typedef void(^MyVoidBlock)(void);
@property (nonatomic, copy) MyVoidBlock myVoidBlock;
@property (nonatomic, copy) NSString *name;
self.name = @"iOS";
self.myVoidBlock = ^{
NSLog(@"%@",self.name);
};
我們會(huì)看到有warning :Capturing 'self' strongly in this block is likely to lead to a retain cycle
提示循環(huán)引用叁温,當(dāng)我們退出ViewController時(shí)再悼,dealloc沒有被調(diào)用
循環(huán)引用的解決
1.__weak和__strong
__weak typeof(self) weakSelf = self;
self.myVoidBlock = ^{
NSLog(@"%@",weakSelf.name);
};
self.myVoidBlock();
當(dāng)我們退出VC時(shí),delloc方法確實(shí)走到了膝但,說明循環(huán)引用解決了冲九。但是如果block內(nèi)存在耗時(shí)操作,當(dāng)我們VC退出后跟束,才會(huì)調(diào)用weakSelf呢莺奸?
__weak typeof(self) weakSelf = self;
self.myVoidBlock = ^{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"%@",weakSelf.name);
});
};
self.myVoidBlock();
-(void)dealloc {
NSLog(@"%s",__func__);
}
dealloc確實(shí)走了,但是我們的打印名字出現(xiàn)了問題
-[ViewController dealloc]
(null)
這明顯不是我們希望的冀宴,我們希望打印完名字之后對象再被釋放灭贷。
self.name = @"iOS";
__weak typeof(self) weakSelf = self;
self.myVoidBlock = ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"%@",strongSelf.name);
});
};
self.myVoidBlock();
打印按照我們的預(yù)期打印。
2.__block解決循環(huán)引用
__block ViewController *vc = self;
self.myVoidBlock = ^{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"%@",vc.name);
vc = nil;
});
};
self.myVoidBlock();
打印結(jié)果正常
iOS
-[ViewController dealloc]
但是如果block沒被調(diào)用則ViewController對象不會(huì)被釋放
3.作為參數(shù)解決循環(huán)引用
self.myVoidBlock = ^(ViewController *vc){
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"%@",vc.name);
});
};
self.myVoidBlock(self);
打印結(jié)果正常
3.Block的底層原理
1.匯編看Block底層
在block前面打斷點(diǎn)略贮,看匯編
我們看到關(guān)鍵信息objc_retainBlock甚疟,在objc源碼中看出objc_retainBlock底層實(shí)現(xiàn)時(shí)
_Block_copy仗岖。下符號(hào)斷點(diǎn)objc_retainBlock研究
1.全局block
void(^block)(void) = ^{
NSLog(@"----");
};
在符號(hào)斷點(diǎn)處objc_retainBlock,讀取寄存器览妖,
register read x0
x0 = 0x0000000102388028 001---Block深入淺出`__block_literal_global
po 0x0000000102388028
<__NSGlobalBlock__: 0x102388028>
signature: "v8@?0"
invoke : 0x102386288 (/private/var/containers/Bundle/Application/00B30C0F-7E4D-4B6C-B351-9EB5A91223DA/001---Blockê∑±???êμ??á∫.app/001---Blockê∑±???êμ??á∫`__29-[ViewController viewDidLoad]_block_invoke)
2.堆block
int a= 10;
void(^block)(void) = ^{
NSLog(@"----%d",a);
};
同樣在objc_retainBlock符號(hào)斷點(diǎn)處轧拄,讀寄存器信息
) register read x0
x0 = 0x000000016f40b4f8
po 0x000000016f40b4f8
<__NSStackBlock__: 0x16f40b4f8>
signature: "v8@?0"
invoke : 0x1009f6264 (/private/var/containers/Bundle/Application/A4407F87-FF50-4D6F-AA84-CCA6CDA6BCA6/001---Blockê∑±???êμ??á∫.app/001---Blockê∑±???êμ??á∫`__29-[ViewController viewDidLoad]_block_invoke)
單步調(diào)試,在objc_retainBlock返回時(shí)讀寄存器
register read x0
x0 = 0x0000000281e3a0d0
po 0x0000000281e3a0d0
<__NSMallocBlock__: 0x281e3a0d0>
signature: "v8@?0"
invoke : 0x1009f6264 (/private/var/containers/Bundle/Application/A4407F87-FF50-4D6F-AA84-CCA6CDA6BCA6/001---Blockê∑±???êμ??á∫.app/001---Blockê∑±???êμ??á∫`__29-[ViewController viewDidLoad]_block_invoke)
2.結(jié)合源碼看block簽名信息
我們在Block_private.h先查看Block的結(jié)構(gòu)源碼地址
#define BLOCK_DESCRIPTOR_1 1
struct Block_descriptor_1 {
uintptr_t reserved;
uintptr_t size;
};
// 可選
#define BLOCK_DESCRIPTOR_2 1
struct Block_descriptor_2 {
// requires BLOCK_HAS_COPY_DISPOSE
BlockCopyFunction copy;
BlockDisposeFunction dispose;
};
#define BLOCK_DESCRIPTOR_3 1
struct Block_descriptor_3 {
// requires BLOCK_HAS_SIGNATURE
const char *signature;
const char *layout; // contents depend on BLOCK_HAS_EXTENDED_LAYOUT
};
struct Block_layout {
void *isa;
volatile int32_t flags; // contains ref count
int32_t reserved;
BlockInvokeFunction invoke;
struct Block_descriptor_1 *descriptor; //
// imported variables
};
Block_layout是Block的底層實(shí)現(xiàn)讽膏,
Block_layout中的flags
第1 位紧帕,釋放標(biāo)記,-般常用 BLOCK_NEEDS_FREE 做 位與 操作桅打,一同傳入 Flags 是嗜, 告知該 block 可釋放。
低16位挺尾,存儲(chǔ)引用計(jì)數(shù)的值;是一個(gè)可選用參數(shù) 第24位鹅搪,低16是否有效的標(biāo)志,程序根據(jù)它來決定是否增加或是減少引用計(jì)數(shù)位的 值;
第25位遭铺,是否擁有拷貝輔助函數(shù)(a copy helper function); 第26位丽柿,是否擁有 block 析構(gòu)函數(shù); 第27位,標(biāo)志是否有垃圾回收;//OS X 第28位魂挂,標(biāo)志是否是全局block;
第30位甫题,與 BLOCK_USE_STRET 相對,判斷是否當(dāng)前 block 擁有一個(gè)簽名涂召。用于 runtime 時(shí)動(dòng)態(tài)調(diào)用坠非。
我們在Block_descriptor_3看到了關(guān)于簽名的內(nèi)容signature,但是Block_descriptor_3怎么能得到呢
我們在runtime.cpp看到了如下內(nèi)容
#if 0
static struct Block_descriptor_1 * _Block_descriptor_1(struct Block_layout *aBlock)
{
return aBlock->descriptor;
}
#endif
static struct Block_descriptor_2 * _Block_descriptor_2(struct Block_layout *aBlock)
{
if (! (aBlock->flags & BLOCK_HAS_COPY_DISPOSE)) return NULL;
uint8_t *desc = (uint8_t *)aBlock->descriptor;
desc += sizeof(struct Block_descriptor_1);
return (struct Block_descriptor_2 *)desc;
}
static struct Block_descriptor_3 * _Block_descriptor_3(struct Block_layout *aBlock)
{
if (! (aBlock->flags & BLOCK_HAS_SIGNATURE)) return NULL;
uint8_t *desc = (uint8_t *)aBlock->descriptor;
desc += sizeof(struct Block_descriptor_1);
if (aBlock->flags & BLOCK_HAS_COPY_DISPOSE) {
desc += sizeof(struct Block_descriptor_2);
}
return (struct Block_descriptor_3 *)desc;
}
Block_descriptor_3的讀取果正,先通過flags判斷是否存在炎码,然后再通過內(nèi)存平移得到
我們通過拿到的字符串簽名,查看[NSMethodSignature signatureWithObjCTypes:"v8@?0"]
<NSMethodSignature: 0x80bccfb625c2193f>
number of arguments = 1
frame size = 224
is special struct return? NO
return value: -------- -------- -------- --------
type encoding (v) 'v'
flags {}
modifiers {}
frame {offset = 0, offset adjust = 0, size = 0, size adjust = 0}
memory {offset = 0, size = 0}
argument 0: -------- -------- -------- --------
type encoding (@) '@?'
flags {isObject, isBlock}
modifiers {}
frame {offset = 0, offset adjust = 0, size = 8, size adjust = 0}
memory {offset = 0, size = 8}
3.Block的三層Copy
我們分析__block的對象類型
__block NSString *lg_name = [NSString stringWithFormat:@"cooci"];
void (^block1)(void) = ^{ // block_copy
lg_name = @"LG_Cooci";
NSLog(@"LG_Block - %@",lg_name);
// block 內(nèi)存
};
block1();
經(jīng)過clang編譯后block的結(jié)構(gòu)是
struct __main_block_impl_0 {
struct __block_impl impl;
struct __main_block_desc_0* Desc;
__Block_byref_lg_name_0 *lg_name; // by ref
__main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, __Block_byref_lg_name_0 *_lg_name, int flags=0) : lg_name(_lg_name->__forwarding) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
通過clang查看編譯后的cpp秋泳,再結(jié)合block源碼
1.第一層copy潦闲。
我們知道我們創(chuàng)建的Block在引用外部變量的情況下是棧block,但是通過變量持有就變成堆block迫皱。因?yàn)榻?jīng)過了objc_retainBlock歉闰,底層實(shí)現(xiàn)_Block_copy。
因?yàn)槭菑臈5蕉炎科穑覀冎谎芯織opy
void *_Block_copy(const void *arg) {
struct Block_layout *result =
(struct Block_layout *)malloc(aBlock->descriptor->size);
if (!result) return NULL;
memmove(result, aBlock, aBlock->descriptor->size); // bitcopy first
// reset refcount
result->flags &= ~(BLOCK_REFCOUNT_MASK|BLOCK_DEALLOCATING); // XXX not needed
result->flags |= BLOCK_NEEDS_FREE | 2; // logical refcount 1
_Block_call_copy_helper(result, aBlock);
// Set isa last so memory analysis tools see a fully-initialized object.
result->isa = _NSConcreteMallocBlock;
return result;
}
我們看到重新malloc一個(gè)Block,并且memmove和敬,可知也把lg_namecopy進(jìn)去了,這是第一次copy
2.第二層copy
在_Block_copy中我們看到_Block_call_copy_helper
static void _Block_call_copy_helper(void *result, struct Block_layout *aBlock)
{
struct Block_descriptor_2 *desc = _Block_descriptor_2(aBlock);
if (!desc) return;
(*desc->copy)(result, aBlock); // do fixup
}
我們發(fā)現(xiàn)了 (*desc->copy)(result, aBlock)既绩,在clang下看一下desc的結(jié)構(gòu)
static struct __main_block_desc_0 {
size_t reserved;
size_t Block_size;
void (*copy)(struct __main_block_impl_0*, struct __main_block_impl_0*);
void (*dispose)(struct __main_block_impl_0*);
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0), __main_block_copy_0, __main_block_dispose_0};
(*desc->copy)在我們實(shí)例中的實(shí)現(xiàn)是__main_block_copy_0概龄,
static void __main_block_copy_0(struct __main_block_impl_0*dst, struct __main_block_impl_0*src) {
_Block_object_assign((void*)&dst->lg_name, (void*)src->lg_name, 8/*BLOCK_FIELD_IS_BYREF*/);
}
在源碼中查看_Block_object_assign實(shí)現(xiàn)还惠,我們只看__blcok 對象的內(nèi)容
void _Block_object_assign(void *destArg, const void *object, const int flags) {
const void **dest = (const void **)destArg;
case BLOCK_FIELD_IS_BYREF:
/*******
// copy the onstack __block container to the heap
// Note this __weak is old GC-weak/MRC-unretained.
// ARC-style __weak is handled by the copy helper directly.
__block ... x;
__weak __block ... x;
[^{ x; } copy];
********/
*dest = _Block_byref_copy(object);
break;
}
查看_Block_byref_copy主要代碼
struct Block_byref *copy = (struct Block_byref *)malloc(src->size);
copy->isa = NULL;
// byref value 4 is logical refcount of 2: one for caller, one for stack
copy->flags = src->flags | BLOCK_BYREF_NEEDS_FREE | 4;
// 問題 - block 內(nèi)部 持有的 Block_byref 鎖持有的對象 是不是同一個(gè)
copy->forwarding = copy; // patch heap copy to point to itself
src->forwarding = copy; // patch stack to point to heap copy
copy->size = src->size;
if (src->flags & BLOCK_BYREF_HAS_COPY_DISPOSE) {
// Trust copy helper to copy everything of interest
// If more than one field shows up in a byref block this is wrong XXX
struct Block_byref_2 *src2 = (struct Block_byref_2 *)(src+1);
struct Block_byref_2 *copy2 = (struct Block_byref_2 *)(copy+1);
copy2->byref_keep = src2->byref_keep;
copy2->byref_destroy = src2->byref_destroy;
if (src->flags & BLOCK_BYREF_LAYOUT_EXTENDED) {
struct Block_byref_3 *src3 = (struct Block_byref_3 *)(src2+1);
struct Block_byref_3 *copy3 = (struct Block_byref_3*)(copy2+1);
copy3->layout = src3->layout;
}
(*src2->byref_keep)(copy, src);
我們看到struct Block_byref *copy = (struct Block_byref *)malloc(src->size);這是第二層copy饲握。
3.第三層copy
在_Block_byref_copy中我們看到src2->byref_keep私杜,查看clang下代碼
struct __Block_byref_lg_name_0 {
void *__isa;
__Block_byref_lg_name_0 *__forwarding;
int __flags;
int __size;
void (*__Block_byref_id_object_copy)(void*, void*);
void (*__Block_byref_id_object_dispose)(void*); // 5*8 = 40
NSString *lg_name;
};
看源碼關(guān)于byref的定義
struct Block_byref {
void *isa;
struct Block_byref *forwarding;
volatile int32_t flags; // contains ref count
uint32_t size;
};
struct Block_byref_2 {
// requires BLOCK_BYREF_HAS_COPY_DISPOSE
BlockByrefKeepFunction byref_keep; // 結(jié)構(gòu)體 __block 對象
BlockByrefDestroyFunction byref_destroy;
};
可知src2->byref_keep,在clang中調(diào)用的是__Block_byref_id_object_copy救欧,看到賦值是__Block_byref_id_object_copy_131
static void __Block_byref_id_object_copy_131(void *dst, void *src) {
_Block_object_assign((char*)dst + 40, *(void * *) ((char*)src + 40), 131);
}
_Block_object_assign中
//flag是131 128+3 為BLOCK_BYREF_CALLER和BLOCK_FIELD_IS_OBJECT
void _Block_object_assign(void *destArg, const void *object, const int flags) {
const void **dest = (const void **)destArg;
switch (os_assumes(flags & BLOCK_ALL_COPY_DISPOSE_FLAGS)) {
case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT:
case BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK:
*dest = object;
break;
}
完成三層copy衰粹。
4.Block的銷毀
首先調(diào)用_Block_release
void _Block_release(const void *arg) {
struct Block_layout *aBlock = (struct Block_layout *)arg;
if (!aBlock) return;
if (aBlock->flags & BLOCK_IS_GLOBAL) return;
if (! (aBlock->flags & BLOCK_NEEDS_FREE)) return;
if (latching_decr_int_should_deallocate(&aBlock->flags)) {
_Block_call_dispose_helper(aBlock);
_Block_destructInstance(aBlock);
free(aBlock);
}
}
static void _Block_call_dispose_helper(struct Block_layout *aBlock)
{
struct Block_descriptor_2 *desc = _Block_descriptor_2(aBlock);
if (!desc) return;
(*desc->dispose)(aBlock);
}
desc->dispose對應(yīng)cpp中的__main_block_dispose_0
static void __main_block_dispose_0(struct __main_block_impl_0*src) {_Block_object_dispose((void*)src->lg_name, 8/*BLOCK_FIELD_IS_BYREF*/);}
在Block源碼_Block_object_dispose中 flags為8 BLOCK_FIELD_IS_BYREF
void _Block_object_dispose(const void *object, const int flags) {
switch (os_assumes(flags & BLOCK_ALL_COPY_DISPOSE_FLAGS)) {
case BLOCK_FIELD_IS_BYREF | BLOCK_FIELD_IS_WEAK:
case BLOCK_FIELD_IS_BYREF:
// get rid of the __block data structure held in a Block
_Block_byref_release(object);
break;
}
static void _Block_byref_release(const void *arg) {
struct Block_byref *byref = (struct Block_byref *)arg;
// dereference the forwarding pointer since the compiler isn't doing this anymore (ever?)
byref = byref->forwarding;
if (byref->flags & BLOCK_BYREF_NEEDS_FREE) {
int32_t refcount = byref->flags & BLOCK_REFCOUNT_MASK;
os_assert(refcount);
if (latching_decr_int_should_deallocate(&byref->flags)) {
if (byref->flags & BLOCK_BYREF_HAS_COPY_DISPOSE) {
struct Block_byref_2 *byref2 = (struct Block_byref_2 *)(byref+1);
(*byref2->byref_destroy)(byref);
}
free(byref);
}
}
}
byref2->byref_destroy對應(yīng)cpp中的__Block_byref_id_object_dispose_131
static void __Block_byref_id_object_dispose_131(void *src) {
_Block_object_dispose(*(void * *) ((char*)src + 40), 131);
}
為什么用會(huì)有src + 40我們來看Block_byref結(jié)構(gòu)
struct __Block_byref_lg_name_0 {
void *__isa;
__Block_byref_lg_name_0 *__forwarding;
int __flags;
int __size;
void (*__Block_byref_id_object_copy)(void*, void*);
void (*__Block_byref_id_object_dispose)(void*);
NSString *lg_name;
};
131等于BLOCK_BYREF_CALLER的128加上BLOCK_FIELD_IS_OBJECT的3
_Block_object_dispose不做處理。
_Block_release===》Block 中desc的dispose====〉_Block_object_dispose
clang -x objective-c -rewrite-objc -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk
clang -rewrite-objc -fobjc-arc -framework Foundation main2.m -o main2.cpp
Xcrun