0
我測試的互聯網連接與Reachability
和dispatch_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;
但我並沒有改變任何東西。
請告訴我上面的代碼,爲什麼它被稱爲多次回事?
什麼是使用此塊可能發生的危險?
我知道這就是爲什麼我叫'didappear',但爲什麼它一次被稱爲5或3次,它應該調用一次'viewdidappear' –
如果你懷疑這是事實,你可以通過在你的'testInternetConnection'方法的第一行放置一個'breakpoint',然後檢查'Debug Navigator'選項卡(在左邊的導航窗格的右邊第三個)來確認(或反駁)它被這個方法調用)來查看方法調用堆棧鏈。 –
@MordFustang:好的我已經更新了我的答案以涵蓋您編輯的問題。 –