0

我测试互联网连接,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;,但我没有更改任何内容。

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

使用此块可能存在哪些危险?

4

1 回答 1

4

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

更新:好的,你稍微改变了你的问题。您收到 5 条“确实消失”消息的原因是因为您从未停止通知程序。只要它在运行,可达性就会一直保持生命,所以取消你的引用并不会杀死它。您需要[internetReachableFoo stopNotifier]在取消之前明确说明。

于 2013-04-01T19:14:35.170 回答