gpt4 book ai didi

IOS dispatch_get_main_queue()被多次调用

转载 作者:行者123 更新时间:2023-11-28 19:10:49 26 4
gpt4 key购买 nike

我使用 Reachabilitydispatch_async(dispatch_get_main_queue() 测试互联网连接当我测试以下代码时,它可以正常工作,但会被多次调用。

家长:

@protocol RootViewDelegate <NSObject>
@optional
-(void)internetIsDownGoToRoot;
@end
- (void)testInternetConnection
{
internetReachableFoo = [ReachabilityTony reachabilityWithHostname:@"www.google.com"];

__weak typeof(self) weakSelf = self;
// Internet is reachable
internetReachableFoo.reachableBlock = ^(ReachabilityTony *reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Yayyy, we have the interwebs!");
[weakSelf sendLoginRequest];
});
};
// Internet is not reachable
internetReachableFoo.unreachableBlock = ^(ReachabilityTony *reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Someone broke the internet :(");
CloudConnection *sharedInstance=[CloudConnection sharedInstance];
sharedInstance.isUserLoggedIN=NO;
//update login button
[weakSelf updateButtons];
[weakSelf notifyChild];

});
};
[internetReachableFoo startNotifier];
}
-(void)viewDidAppear:(BOOL)animated
{
[self testInternetConnection];
}
-(void)viewWillDisappear:(BOOL)animated
{
internetReachableFoo= nil;

}
//notify childs no connection come back to root
-(void) notifyChild
{
[delegate internetIsDownGoToRoot];

}

child :

-(void)viewDidAppear:(BOOL)animated
{

NSArray *viewControllers = self.navigationController.viewControllers;
int count = [viewControllers count];
id previousController = [viewControllers objectAtIndex:count - 2];
RootViewController *rvc= previousController;
rvc.delegate=self;


}

-(void)internetIsDownGoToRoot
{
//internet connection is no avaliable go to root
[self.navigationController popToRootViewControllerAnimated:YES];

}

所以这是 parentview 让我说我 push-pop childview 5 次并关闭互联网。我在 nslog 上看到

Someone broke the internet :(
Someone broke the internet :(
Someone broke the internet :(
Someone broke the internet :(
Someone broke the internet :(

如您所见,我添加了 internetReachableFoo= nil; 但我没有更改任何内容。

上面的代码是怎么回事,为什么会被多次调用?

使用这个 block 可能有什么危险?

最佳答案

它会被多次调用,因为每次弹出子节点时,根节点都会获取 -viewDidAppear: 并调用 -testInternetConnection,这会重新运行可达性测试。

更新:好的,您已经稍微更改了您的问题。您收到 5 条“确实消失”消息的原因是因为您从不停止通知程序。只要它正在运行,可达性就会使自己保持事件状态,因此清除您的引用并不会杀死它。你需要明确地说出 [internetReachableFoo stopNotifier],然后再将其删除。

关于IOS dispatch_get_main_queue()被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15749902/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com