NSRunLoop

157 阅读1分钟

RunLoop其实是iOS中的一种消息机制的处理模式。

举例

由定时器来例子,一般分为如下几种:

第一种:

用这种方式,需要手动添加到runloop中才会执行,如下: [[NSRunLoop currentRunLoop] addTimer:_timer forMode:

第二种

这种方式系统自动添加到runloop中,无需手动添加。

注意

在子线程上,必须要手动开启runloop。而且子线程上面的定时器,必须要在子线程里面销毁,否则会造成runloop资源的浪费。不过现在基本都用的是ARC,系统会在一个子线程完成的时候销毁掉这个子线程,因此子线程的RunLoop也就跟着自动销毁了。

参数

scheduledTimerWithTimeInterval:(NSTimeInterval)seconds 设置一个时间间隔。

target:(id)aTarget 表示发送的对象,如self

selector:(SEL)aSelector 在时间间隔内执行的方法

userInfo:(id)userInfo 此参数可以为nil

repeats:(BOOL)yesOrNo

当YES时,定时器会不断循环直至失效或被释放,当NO时,定时器会循环发送一次就失效。

调用一次定时器

_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeAction:) userInfo:nil repeats:NO];

重复调用定时器

_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];

NSTimer销毁的问题

1.多次调用前提前销毁,保证主线程中只有一个NSTimer在运行。

2.使用完毕后销毁timer,否者不会走dealloc方法。

原因: 销毁timer的时候不能直接timer=nil这样设置,因为创建NSTimer加入到runloop后, 除了ViewController之外系统也会强引用NSTimer对象,当调用invalidate方法时, 就可以移除runloop了, 系统也会取消对NSTimer的强引用,然后在设置timer=nil即可。