iphone - 可达性代码阻塞主线程

标签 iphone ios multithreading reachability

我目前正在开发一款需要我检查可达性的应用。

因此,我开始查找资料并找到了 DDG 和 Apple 的代码。我决定使用 Apple 最新的可达性代码。

我导入了它,并且按照 Apple 样本中的建议,我想到了以下注册方式:

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

    //check for local connection and start notifier
    client = [[Reachability reachabilityForInternetConnection] retain];
    [client startNotifier];

    //check for server connection and start notifier
    server = [[Reachability reachabilityWithHostName:SERVER_HOST_NAME] retain];
    [server startNotifier];

    //check for other server and start notifier
    otherServer = [[Reachability reachabilityWithHostName:OTHER_SERVER_HOST_NAME] retain];
    [otherServer startNotifier];

我在运行应用程序时观察到的是这段代码开始阻塞 UI(阻塞主线程)。在解析主机名之前,我无法与其他 UI 元素交互。现在我知道 Apple 已经声明了有关 DNS 解析并使其异步的警告。

我的问题是,我该如何继续并使其异步?

我是否生成另一个线程并保持运行以便不“释放”可达性对象?

在此先感谢您的帮助! :)

最佳答案

好的。好吧,我发现了问题所在。 >_<

上面发布的代码确实是异步工作的。

但是,我在 notificationHandler: 下编写的代码正在对服务进行同步调用。它是由其他人编写的,因此我花了一些时间才弄清楚那是 UI 卡住的根源。不过,问题已经解决了。我想我会写这篇文章来结束这个问题。 :)

再次感谢!

关于iphone - 可达性代码阻塞主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7549870/

相关文章:

ios - 启动画面问题 iPhone

iphone - UINavigationController 有奇怪的行为

ios - Xcode 6.3 在项目重命名时崩溃

ios - 检测到按下后退以到达当前 View Controller

objective-c - View 更改后 View 属性重置

java - 这个同步块(synchronized block)内发生了什么

iphone - 如何在prepareForSegue之前进行内部润色

java - scjp:线程相关问题

java - 在java中读取大txt文件时使用线程?

ios - 在 UITextView 中获取当前输入的单词