2015-06-03 22 views
1

我試圖使用編輯Objective-C的可達性塊中的變量,這是代碼:「捕獲‘自我’強烈該塊很可能會導致保留循環」使用可達

- (void)testInternetConnection 
{ 
    internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"]; 
    // Internet is reachable 
    internetReachableFoo.reachableBlock = ^(Reachability*reach) 
    { 
     // Update the UI on the main thread 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      NSLog(@"Connessione ad Internet disponibile"); 
      checkConnection = YES; 
      if(!lastConnectionState) 
      { 
       lastConnectionState = YES; 
       if(doItemsDownload) 
        [self displayChoice]; 
      } 
     }); 
    }; 

    // Internet is not reachable 
    internetReachableFoo.unreachableBlock = ^(Reachability*reach) 
    { 
     // Update the UI on the main thread 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      NSLog(@"Connessione ad Internet non disponibile"); 
      checkConnection = NO; 
      lastConnectionState = NO; 
     }); 
    }; 

    [internetReachableFoo startNotifier]; 
} 

其中checkConnection; & lastConnectionState;是在我的@interface上聲明的2個bool; 問題是,訪問這些變量並在此塊內調用[self displayChoice];會給我警告:Capturing 'self' strongly in this block is likely to lead to a retain cycle

我該如何避免此錯誤? 我想聲明WeakSelf並宣佈self,但我不知道如何做到這一點的布爾變量

+0

可能重複的[捕獲自強烈在該塊是可能導致一個保留週期(http://stackoverflow.com/questions/14556605/capturing-self-strongly-in-this-block-可能導致保留週期) –

+0

問題是你的對象(self在這裏)保留'internetReachableFoo'和internetReachableFoo保留塊並且塊保留它所引用的對象,比如'self '。沒有人可以獲得釋放,因爲每個東西都掛在一個掛在它上面的東西(間接)。重複鏈接的答案解釋了要做什麼。 – danh

回答

0

有一個叫libextobjc,它允許你做的是快速,乾淨weakify和strongify對象cocoapod。

@weakify(self) 
[someblock:^{ 
    @strongify(self) 
}]; 

只要你處理自己,你應該沒問題。我不是100%肯定的布爾值不是一個問題,但我認爲你可以做這樣的事情:

BOOL x = YES; 
@weakify(self, x) 
[someblock:^{ 
    @strongify(self, x) 
}]; 
5

塊中捕獲自強並不總是壞事。如果一個塊正在被立即執行(例如UIView動畫塊),通常沒有風險。

問題出現時,自我強烈地捕獲一個塊,而塊又強烈地捕獲自己。在這種情況下,自我保留塊,塊保留自己,因此都不能釋放 - >保留週期!

爲了避免這種情況,你需要在塊中弱拍自己。的

__weak typeof(self) = self; // CREATE A WEAK REFERENCE OF SELF 
__block BOOL blockDoItemsDownload = doItemsDownload; // USE THIS INSTEAD OF REFERENCING ENVIRONMENT VARIABLE DIRECTLY 
__block BOOL blockCheckConnection = checkConnection; 
internetReachableFoo.reachableBlock = ^(Reachability*reach) 
{ 
    // Update the UI on the main thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     NSLog(@"Connessione ad Internet disponibile"); 
     blockCheckConnection = YES; 
     if(!lastConnectionState) 
     { 
      lastConnectionState = YES; 
      if(blockDoItemsDownload)  // Use block variable here 
       [weakSelf displayChoice]; // Use weakSelf in place of self 
     } 
    }); 
}; 
+0

聲明弱自我工作,但2布爾值(checkConnection和doItemsDownload?)它怎麼樣?他們給我同樣的錯誤,但我不能聲明布爾作爲__weak,我該怎麼辦? – Signo

+0

塊通常會複製所有引用的變量如果你想修改一個環境變量,你應該使用它的__block版本,參見答案中的編輯。 – Max

相關問題