block對於其變量都會造成strong reference(強引用),對self也會造成strong reference,而若是self自己對block也是 strong reference 的話,就會造成 strong reference 循環,形成內存泄露。爲了防止這種狀況發生,在block外部應該建立一個week(__block) reference(弱引用類型)。objective-c
因此在block內若是有self的話,通常都會在block外面加一句_block typeof(self) bself = self;ui
例如:spa
__weak typeof(self) weakSelf = self; [weakSelf addLegendFooterWithRefreshingBlock:^{ //do something [weakSelf.footer endRefreshing]; }
//參考網址:http://rocry.com/2012/12/18/objective-c-type-of/?utm_source=tuicoolcode
// AFNetworking的寫法 __weak __typeof(&*self)weakSelf = self; // 個人寫法 __weak __typeof(self) weakSelf = self; // 或者這麼寫 __weak XxxViewController *weakSelf = self; // 或者這麼寫 __weak id weakSelf = self;