0
我测试的互联网连接与Reachability
和dispatch_async(dispatch_get_main_queue()
当我测试下面的代码,它的工作原理,但它被称为多次。IOS 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];
}
儿童:
-(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可以说我推抵扣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;
但我并没有改变任何东西。
请告诉我上面的代码,为什么它被称为多次回事?
什么是使用此块可能发生的危险?
我知道这就是为什么我叫'didappear',但为什么它一次被称为5或3次,它应该调用一次'viewdidappear' –
如果你怀疑这是事实,你可以通过在你的'testInternetConnection'方法的第一行放置一个'breakpoint',然后检查'Debug Navigator'选项卡(在左边的导航窗格的右边第三个)来确认(或反驳)它被这个方法调用)来查看方法调用堆栈链。 –
@MordFustang:好的我已经更新了我的答案以涵盖您编辑的问题。 –