我最近學到了這個技巧,當我必須在塊中引用self時。用ARC在雙塊中捕獲自我
__weak MyObject *safeSelf = self;
[self doWithCompletionBlock:^{
HMFInventoryBatchItemsController *strongSelf = safeSelf;
if (strongSelf) {
[strongSelf doSomethingElse];
}
}];
但我一直在想,如果我有一個塊內的塊?我是否需要再次做同樣的事情?
__weak MyObject *safeSelf = self;
[self doWithCompletionBlock:^{
HMFInventoryBatchItemsController *strongSelf = safeSelf;
if (strongSelf) {
__weak MyObject *saferSelf = strongSelf;
[strongSelf doAnotherThingWithCompletionBlock:^{
HMFInventoryBatchItemsController *strongerSelf = saferSelf;
if (strongerSelf) {
[strongerSelf doSomethingElse];
}
}];
}
}];
或者是這個罰款
__weak MyObject *safeSelf = self;
[self doWithCompletionBlock:^{
HMFInventoryBatchItemsController *strongSelf = safeSelf;
if (strongSelf) {
[strongSelf doAnotherThingWithCompletionBlock:^{
[strongSelf doSomethingElse];
}];
}
}];
爲什麼使用HMFInventoryBatchItemsController重新分配自己* strongSelf = safeSelf;既然自己是塊的所有權? –
除非你想訪問它的ivar,否則你不必在block中做出強有力的參考。 – Elden
我發現這篇文章作爲參考http://amattn.com/2011/12/07/arc_best_practices.html – Hackmodford