RunLoop其实是iOS中的一种消息机制的处理模式。
举例
由定时器来例子,一般分为如下几种:
第一种:
第二种
注意
参数
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即可。