簡體   English   中英

“使用可達性”“在此區塊中強烈捕獲'自我'很可能導致保留周期”

[英]“Capturing 'self' strongly in this block is likely to lead to a retain cycle” using Reachability

我正在嘗試使用Objective-C編輯Reachability塊內的變量,這是代碼:

- (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個布爾值; 問題在於訪問這些變量並調用[self displayChoice]; 在此塊內向我發出警告: Capturing 'self' strongly in this block is likely to lead to a retain cycle

如何避免該錯誤? 我試圖聲明一個WeakSelf並聲明self但我不知道如何為布爾變量做它

在塊中強烈地捕捉自我並不總是壞事。 如果立即執行塊(例如,UIView動畫塊),通常就沒有風險。

當自我強烈捕獲自己的塊,而反過來又強烈捕獲自己的塊時,就會出現問題。 在這種情況下,self將保留塊,而block將保留自身,因此無法釋放->保留循環!

為了避免這種情況,您需要在區塊中弱勢地捕捉自我。

__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
        }
    });
};

有一個名為libextobjc的cocoapod,它可以讓您快速干凈地削弱和增強對象。

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

只要你能自我處理就可以了。 我不確定100%的BOOL值不是問題,但我認為您可以執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM