阻塞主线程的可达性代码
我目前正在开发一个需要我检查可达性的应用程序。
因此,我开始查找资料并找到了 DDG 和 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 元素交互。现在我知道苹果已经对 DNS 解析提出了警告并使其异步。
我的问题是,如何继续使其异步?
我是否会生成另一个线程并保持其运行,以免“释放”Reachability 对象?
预先感谢您的帮助! :)
I'm currently working on an app that requires me to check for reachability.
Owing to that, I started looking stuff up and found DDG and Apple's code. I decided to go with Apple's latest reachability code.
I imported that, and as suggested in Apple's sample, I came up with the following way to register:
[[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];
What I observed when I ran the app was that this code started blocking the UI (blocking the main thread). I could not interact with other UI elements till the host name was resolved. Now I know that Apple has stated a warning about DNS resolution and making it asynchronous.
My question would be, how do I go ahead and make it asynchronous?
Do I spawn another thread and keep it running so as to not "release" the Reachability object?
Thanks in advance for your help! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的。嗯,我知道问题出在哪里了。 >_<
上面发布的代码确实可以异步工作。
但是,我在
notificationHandler:
下编写的代码正在对服务进行同步调用。它是由其他人编写的,因此我花了一些时间才弄清楚这是 UI 冻结的根源。不过,问题已经解决了。我想我应该写这篇文章来结束这个问题。 :)再次感谢!
Okay. Well, I found out what the problem was. >_<
The code posted above does indeed work asynchronously.
However, the code that I had written under
notificationHandler:
was making a synchronous call to a service. It was written by someone else, owing to which it took me some time to figure out that that was the source of the UI freeze. However, problem has been solved. I thought I'd write this post so as to give a closure to this question. :)Thanks again!