如果在子线程上创建一个NSNetServiceBrowser,并调用searchForServicesOfType开始搜索,发现不起作用。查看苹果的文档发现这么一段话:
A network service browser performs all searches asynchronously using the current run loop to execute the search in the background. Results from a search are returned through the associated delegate object, which your client application must provide. Searching proceeds in the background until the object receives a stop message.
To use an NSNetServiceBrowser object to search for services, allocate it, initialize it, and assign a delegate. (If you wish, you can also use the scheduleInRunLoop:forMode: and removeFromRunLoop:forMode: methods to execute searches on a run loop other than the current one.) Once your object is ready, you begin by gathering the list of accessible domains using either the searchForRegistrationDomains or searchForBrowsableDomains methods. From the list of returned domains, you can pick one and use the searchForServicesOfType:inDomain: method to search for services in that domain.
也就是说NSNetServiceBrowser是使用run loop实现不断循环搜索的,类似于NSTimer,主线程中默认开启了runloop,而子线程中默认没有创建runloop,所以需要自己创建并开启一个RunLoop,然后把NSNetServiceBrowser使用scheduleInRunLoop:forMode: 添加到runloop里,这样Bonjour才能开始工作。
在iOS开发中,尝试在子线程启动NSNetServiceBrowser进行Bonjour服务搜索时遇到问题,因为NSNetServiceBrowser在当前运行循环中异步执行搜索。根据苹果文档,搜索过程在后台进行,结果通过委托对象返回。正确使用方法包括分配、初始化对象、设置委托,可以选择在特定运行循环上执行搜索。要开始搜索,首先获取可访问的域,然后选择一个域来查找服务。
464

被折叠的 条评论
为什么被折叠?



