簡體   English   中英

IOS dispatch_get_main_queue()被多次調用

[英]IOS dispatch_get_main_queue() is called multiple times

當我測試以下代碼時,我使用Reachabilitydispatch_async(dispatch_get_main_queue()測試Internet連接,它可以工作,但是被多次調用。

家長:

@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可以說我推送了5次childview並關閉了互聯網。 我在nslog上看到

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

如您所見,我添加了internetReachableFoo= nil; 但我什么都沒改變。

上面的代碼是怎么回事,為什么多次調用它?

使用此塊可能有什么危險?

之所以多次調用它是因為每次您彈出子代時,根節點都會獲得-viewDidAppear:並調用-testInternetConnection ,從而重新運行可達性測試。

更新:好的,您已經稍微更改了您的問題。 之所以收到5條“未消失”消息,是因為您從未停止過通知者。 可達性只要在運行中就可以保持活躍,因此完善您的參考文獻不會殺死它。 您需要在[internetReachableFoo stopNotifier]之前先明確說出[internetReachableFoo stopNotifier]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM