2013-04-01 52 views
0

我测试的互联网连接与Reachabilitydispatch_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;但我并没有改变任何东西。

请告诉我上面的代码,为什么它被称为多次回事?

什么是使用此块可能发生的危险?

回答

4

它被称为多次,因为每次你弹出孩子,根获得-viewDidAppear:并调用-testInternetConnection,它重新运行可达性测试。

更新:确定你已经略有改变你的问题。为什么你得到5“消失”的消息是因为你永远不会停止通知。只要它在运行,可达性就会保持自己的活力,因此扼杀你的参考并不会消灭它。在清除它之前,您需要明确地说出[internetReachableFoo stopNotifier]

+0

我知道这就是为什么我叫'didappear',但为什么它一次被称为5或3次,它应该调用一次'viewdidappear' –

+0

如果你怀疑这是事实,你可以通过在你的'testInternetConnection'方法的第一行放置一个'breakpoint',然后检查'Debug Navigator'选项卡(在左边的导航窗格的右边第三个)来确认(或反驳)它被这个方法调用)来查看方法调用堆栈链。 –

+0

@MordFustang:好的我已经更新了我的答案以涵盖您编辑的问题。 –