RunLoop 的几个run 方法

本文深入探讨了NSRunLoop在iOS开发中的应用,包括其核心方法如run、runMode:beforeDate和runUntilDate的详细解释及使用场景。通过实例演示如何有效控制事件循环,确保程序在指定时间内响应输入或处理任务。

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

Running a Loop

1,run:


Puts the receiver into a permanent loop, during which time it processes data from all attached input sources.


Discussion

If no input sources or timers are attached to the run loop, this method exits immediately; 

otherwise, it runs the receiver in the NSDefaultRunLoopMode by repeatedly invoking runMode:beforeDate:

In other words, this method effectively begins an infinite loop that processes data from the run loop’s input sources and timers.

Manually removing all known input sources and timers from the run loop is not a guarantee that the run loop will exit. OS X can install and remove additional input sources as needed to process requests targeted at the receiver’s thread. Those sources could therefore prevent the run loop from exiting.


If you want the run loop to terminate, you shouldn't use this method. Instead, use one of the other run methods and also check other arbitrary conditions of your own, in a loop. A simple example would be:

BOOL shouldKeepRunning = YES;        // global
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);

where shouldKeepRunning is set to NO somewhere else in the program.


2,- runMode:beforeDate:


Runs the loop once, blocking for input in the specified mode until a given date.


Return Value

YES if the run loop ran and processed an input source or if the specified timeout value was reached; otherwise,NO if the run loop could not be started.


Discussion

If no input sources or timers are attached to the run loop, this method exits immediately and returns NO;


 otherwise, it returns after either the first input source is processed or limitDate is reached. (每次只处理一个事件,所以runUntilDate 以及 run 要循环调用此方法, 具体原因参考RunLoop 事件处理过程


Manually removing all known input sources and timers from the run loop does not guarantee that the run loop will exit immediately. OS X may install and remove additional input sources as needed to process requests targeted at the receiver’s thread. Those sources could therefore prevent the run loop from exiting.


NOTE

    A timer is not considered an input source and may fire multiple times while waiting for this method to return




3,- runUntilDate:


If no input sources or timers are attached to the run loop, this method exits immediately; 


otherwise, it runs the receiver in the NSDefaultRunLoopMode by repeatedly invoking runMode:beforeDate: until the specified expiration date.













转载于:https://my.oschina.net/u/255456/blog/522567

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值