2013-04-01 82 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:好的我已經更新了我的答案以涵蓋您編輯的問題。 –