block 知識點 ---- Objective-C 高階程式設計 iOS 與 OS X 多執行緒記憶體管理 學習筆記
阿新 • • 發佈:2019-02-07
1. block捕捉變數:
結論:只有呼叫_Block_copy 才能持有截獲的附有 __strong 修飾符的物件型別的自動變數值。
block 中使用物件型別的自動變數時,除以下情形,推薦使用copy方法:
- “When the Block is returned from a function
- When the Block is assigned to a member variable of id or the Block type class, with a __strong qualifier
- When the Block is passed to a method, including “usingBlock” in the Cocoa Framework, or a Grand Central Dispatch API”
blk_t blk 執行copy情況:
blk_t blk; { id array = [[NSMutableArray alloc] init]; blk = [^(id obj) { [array addObject:obj]; NSLog(@"array count = %ld", [array count]); } copy]; }//由於copy,所以block持有array,所以超出作用域依然存在 blk([[NSObject alloc] init]); //array count = 1 blk([[NSObject alloc] init]); //array count = 2 blk([[NSObject alloc] init]); //array count = 3
blk_t blk 不執行copy情況:
{ id array = [[NSMutableArray alloc] init]; blk = ^(id obj) { [array addObject:obj]; NSLog(@"array count = %ld", [array count]); }; } //超出id 作用域,_ _strong 修飾的物件被釋放。 blk([[NSObject alloc] init]); //outPut:程式強行結束。 blk([[NSObject alloc] init]); blk([[NSObject alloc] init]);”