"在这个区块中强烈捕捉'自我'可能会导致保留周期"使用可达性

LS_*_*LS_ 1 objective-c

我正在尝试使用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];
}
Run Code Online (Sandbox Code Playgroud)

checkConnection;lastConnectionState;我的@interface声明2个BOOL; 问题是访问这些变量并[self displayChoice];在此块内调用会给出警告:Capturing 'self' strongly in this block is likely to lead to a retain cycle

我怎么可能避免这个错误?我尝试声明WeakSelf并声明self但我不知道如何为bool变量执行此操作

Max*_*Max 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
        }
    });
};
Run Code Online (Sandbox Code Playgroud)