[英]Avoiding the “capturing self strongly in this block is likely to lead to a retain cycle” message
[英]“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.