我試圖使用編輯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
,但我不知道如何做到這一點的布爾變量
可能重複的[捕獲自強烈在該塊是可能導致一個保留週期(http://stackoverflow.com/questions/14556605/capturing-self-strongly-in-this-block-可能導致保留週期) –
問題是你的對象(self在這裏)保留'internetReachableFoo'和internetReachableFoo保留塊並且塊保留它所引用的對象,比如'self '。沒有人可以獲得釋放,因爲每個東西都掛在一個掛在它上面的東西(間接)。重複鏈接的答案解釋了要做什麼。 – danh