0

我只想执行一些代码,并且只有当我连接到互联网时:

//Reachability

[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(reachabilityChanged:)
                                      name:kReachabilityChangedNotification
                                      object:nil];

Reachability * reach = [Reachability reachabilityWithHostname:@"www.dropbox.com"];

reach.reachableBlock = ^(Reachability * reachability)
{
    dispatch_async(dispatch_get_main_queue(), ^{

        NSLog(@"Block Says Reachable");

        connect = @"yes";

    });
};

reach.unreachableBlock = ^(Reachability * reachability)
{
    dispatch_async(dispatch_get_main_queue(), ^{

        connect = @"no";


    });

};

[reach startNotifier];

//Reachability

if (connect == @"no") {

    UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"" message:@"There is no internet connection. Please connect to the internet. If you are already connected, there might be a problem with our server. Try again in a moment." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
    [alert1 show];

} else if (titleSet == NULL){

    UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"" message:@"Please select a group or create a new one" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
    [alert1 show];

}else if (NavBar.topItem.title.length < 1){

    UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"" message:@"Please select a group or create a new one" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
    [alert1 show];

} else if (newmessagename.text.length < 4){

    UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"" message:@"Please give a name to your event that is at least 4 characters long" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
    [alert1 show];

}

似乎代码没有按顺序执行。我认为检查 Internet 连接所花费的时间比执行代码所花费的时间要多。我怎样才能解决这个问题?请不要告诉我将代码直接放在括号中connect = @"no";的位置。

4

2 回答 2

0

这些块不是按顺序执行的,它们是异步执行的。

这意味着您无法判断块内的代码何时会被调用。使用该块的代码可能会在您的方法的其余部分之前完成并执行(但这不太可能,尤其是在 Internet 连接的情况下)。

您应该将您ifs的方法放在一个在有效时间调用的方法中。这一次可能是您收到来自您的块的响应,或者,如果我的记忆正确,[reach startNotifier];可以在可达性状态发生变化时通知您,这似乎是您的reachabilityChanged:方法:

-(void) reachabilityChanged:(id) parameter
{
   //Query reachability and notify / cache as required.
} 
于 2012-11-27T17:43:29.087 回答
0

当然它不是按顺序执行的,这些方法的全部目的是在您获得可达性响应时停止 ui 冻结。基本上,您设置了可达性响应,并在尚未检查任何内容时立即询问结果。你真正要做的是将它移动到括号内。

您可以做的其他事情是使用这些结果创建一个函数,并在两个块中调用此函数。

如果您想在视图控制器的负载上或在显示其他任何内容之前使用它,那么您必须在显示此控制器之前检查可访问性,或者添加“加载”屏幕。

编辑:我不明白的其他事情是,这些可达性方法在获得结果时似乎会触发一个块,但您也在注册通知。而且我没有看到您为此发布通知。您在这里使用了 2 个异步方法(块和通知)

于 2012-11-27T17:43:41.277 回答