IOS dispatch_get_main_queue()被多次调用

时间:2013-04-01 19:04:55

标签: ios objective-c objective-c-blocks reachability

我使用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];

}

子:

-(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];

}

所以这是父视图让我说我推送弹出儿童视图5次并关闭互联网。我在nslog上看到了

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

正如您所看到的,我添加了internetReachableFoo= nil;,但我没有改变任何内容。

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

使用此阻止可能有什么危险?

1 个答案:

答案 0 :(得分:4)

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

更新:好的,您已经稍微改变了一下您的问题。你之所以得到5&#34;之所以消失了#34;消息是因为你永远不会停止通知。只要它可以运行,可达性就会保持活力,因此,将你的参考文件排除在外并不会导致死亡。在填写之前,您需要明确说出[internetReachableFoo stopNotifier]