我正在尝试使用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个bool;
问题是访问这些变量并在此块中调用[self displayChoice];
会给出警告:Capturing 'self' strongly in this block is likely to lead to a retain cycle
我怎样才能避免这个错误?
我尝试声明WeakSelf
并声明self
,但我不知道如何为bool变量执行此操作
答案 0 :(得分: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
}
});
};
答案 1 :(得分:0)
有一个名为libextobjc的cocoapod,它允许你做的是快速而干净地削弱和强化对象。
@weakify(self)
[someblock:^{
@strongify(self)
}];
只要你处理自己,你应该没问题。我不是100%确定BOOL值不是问题,但我认为你可以这样做:
BOOL x = YES;
@weakify(self, x)
[someblock:^{
@strongify(self, x)
}];