本系列博文总结自《Pro Multithreading and Memory Management for iOS and OS X with ARC》
在上一篇文章中,我们讲了很多关于 block 和基础变量的内存管理,接着我们聊聊 block 和对象的内存管理,如 block 经常会碰到的循环引用问题等等。
获取对象
照例先来段代码轻松下,瞧瞧 block 是怎么获取外部对象的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/********************** capturing objects **********************/ typedef void (^blk_t)(id obj); blk_t blk; - (void)viewDidLoad { [self captureObject]; blk([[NSObject alloc] init]); blk([[NSObject alloc] init]); blk([[NSObject alloc] init]); } - (void)captureObject { id array = [[NSMutableArray alloc] init]; blk = [^(id obj) { [array addObject:obj]; NSLog(@"array count = %ld", [array count]); } copy]; } |
翻译后的关键代码摘录如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
/* a struct for the Block and some functions */ struct __main_block_impl_0 { struct __block_impl impl; struct __main_block_desc_0 *Desc; id __strong array; __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, id __strong _array, int flags=0) : array(_array) { impl.isa = &_NSConcreteStackBlock; impl.Flags = flags; impl.FuncPtr = fp; Desc = desc; } }; static void __main_block_func_0(struct __main_block_impl_0 *__cself, id obj) { id __strong array = __cself->array; [array addObject:obj]; NSLog(@"array count = %ld", [array count]); } static void __main_block_copy_0(struct __main_block_impl_0 *dst, __main_block_impl_0 *src) { _Block_object_assign(&dst->array, src->array, BLOCK_FIELD_IS_OBJECT); } static void __main_block_dispose_0(struct __main_block_impl_0 *src) { _Block_object_dispose(src->array, BLOCK_FIELD_IS_OBJECT); } struct static struct __main_block_desc_0 { unsigned long reserved; unsigned long 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 }; /* Block literal and executing the Block */ blk_t blk; { id __strong array = [[NSMutableArray alloc] init]; blk = &__main_block_impl_0(__main_block_func_0, &__main_block_desc_0_DATA, array, ŧ例先来段代码轻松下,瞧瞧 block 是怎么获取外部对象的
翻译后的关键代码摘录如下
|