iOS中Bonjour:NSNetServiceBrowser在子线程上使用

iOS中的NSNetServiceBrowser在子线程上进行服务搜索时需要运行在RunLoop中。根据苹果文档,它异步地在当前RunLoop执行搜索,并通过委托对象返回结果。要使用NSNetServiceBrowser,需要初始化、分配委托,可以选择在特定RunLoop上执行搜索。首先获取域名列表,然后选择一个域名进行服务类型搜索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在子线程上创建一个NSNetServiceBrowser,并调用searchForServicesOfType开始搜索,是不会起作用。因为他需要在runloop中实现,苹果的文档有这么一段话:

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 searchForBrowsableDomainsmethods. 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才能开始工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值