IOS dispatch_get_main_queue()被多次调用

我使用Reachabilitydispatch_async(dispatch_get_main_queue()testing互联网连接,当我testing下面的代码的时候,它会被多次调用。

家长:

 @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]; } 

所以这是父视图可以说我push-pop的childview 5次,并closures互联网。 我在nslog上看到

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

你可以看到我添加了internetReachableFoo= nil; 但我没有改变任何东西。

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

使用这个块的可能的危险是什么?

它被称为多次,因为每次你popup孩子,根得到-viewDidAppear:和调用-testInternetConnection ,它重新运行可达性testing。

更新:好的,你已经稍微改变了你的问题。 你为什么得到5“消失”的消息是因为你永远不会停止通知。 可达性只要运行就保持活跃状态​​,因此扼杀你的参考并不能杀死它。 在清除之前,你需要明确地说[internetReachableFoo stopNotifier]