NSTimer用法小结

简介: <br><br><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:Arial; font-size:14px; line-height:26px"> <span style="font-size:18px">Timers的替代方法</span></p>


Timers的替代方法

如果只是要延迟消息的发送,可以使用NSObject的方法

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait

+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget


创建Timer的三种方法

1.scheduling a timer with the current run loop 

2.creating a timer that you later register with a run loop

3.initializing a timer with a given fire date

Scheduled Timers

以下两个方法自动注册新创建的timer到当前NSRunLoop对象,NSRunLoop的模式为默认的NSDefaultRunLoopMode

  • + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds invocation:(NSInvocation *)invocation repeats:(BOOL)repeats
  • + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats

只发送一次
[plain]  view plain copy print ?
  1. - (IBAction)startOneOffTimer:sender {  
  2.    
  3.     [NSTimer scheduledTimerWithTimeInterval:2.0  
  4.              target:self  
  5.              selector:@selector(targetMethod:)  
  6.              userInfo:[self userInfo]  
  7.              repeats:NO];  
  8. }  


重复发送消息

注:创建重复发送消息的timer一般需要保存一个引用,因为需要在某个时刻停止发送消息

[plain]  view plain copy print ?
  1. - (IBAction)startRepeatingTimer:sender {  
  2.    
  3.     NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5  
  4.                               target:self selector:@selector(timerFireMethod:)  
  5.                               userInfo:[self userInfo] repeats:YES];  
  6.     self.repeatingTimer = timer;  
  7. }  


Unscheduled Timers

创建未注册的timer,使用时调用addTimer:forMode注册到NSRunLoop对象

[plain]  view plain copy print ?
  1. - (IBAction)createUnregisteredTimer:sender {  
  2.    
  3.     NSMethodSignature *methodSignature = [self methodSignatureForSelector:@selector(invocationMethod:)];  
  4.     NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];  
  5.     [invocation setTarget:self];  
  6.     [invocation setSelector:@selector(invocationMethod:)];  
  7.     NSDate *startDate = [NSDate date];  
  8.     [invocation setArgument:&startDate atIndex:2];  
  9.    
  10.     NSTimer *timer = [NSTimer timerWithTimeInterval:0.5 invocation:invocation repeats:YES];  
  11.     self.unregisteredTimer = timer;  
  12. }  

[plain]  view plain copy print ?
  1. - (IBAction)startUnregisteredTimer:sender {  
  2.     if (unregisteredTimer != nil) {  
  3.         NSRunLoop *runLoop = [NSRunLoop currentRunLoop];  
  4.         [runLoop addTimer:unregisteredTimer forMode:NSDefaultRunLoopMode];  
  5.     }  
  6. }  


Initializing a Timer with a Fire Date

创建一个拥有指定发送日期的timer

[plain]  view plain copy print ?
  1. - (IBAction)startFireDateTimer:sender {  
  2.     NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:1.0];  
  3.     NSTimer *timer = [[NSTimer alloc] initWithFireDate:fireDate  
  4.                                       interval:0.5  
  5.                                       target:self  
  6.                                       selector:@selector(countedtargetMethod:)  
  7.                                       userInfo:[self userInfo]  
  8.                                       repeats:YES];  
  9.    
  10.     timerCount = 1;  
  11.     NSRunLoop *runLoop = [NSRunLoop currentRunLoop];  
  12.     [runLoop addTimer:timer forMode:NSDefaultRunLoopMode];  
  13.     [timer release];  
  14. }  

Stopping a Timer

[plain]  view plain copy print ?
  1. - (IBAction)stopRepeatingTimer:sender {  
  2.     [repeatingTimer invalidate];  
  3.     self.repeatingTimer = nil;  
  4. }  
  5.    
[plain]  view plain copy print ?
  1. 也可以从timer发送的消息中停止timer  
[plain]  view plain copy print ?
  1. - (void)countedtargetMethod:(NSTimer*)theTimer {  
  2.    
  3.     NSDate *startDate = [[theTimer userInfo] objectForKey:@"StartDate"];  
  4.     NSLog(@"Timer started on %@; fire count %d", startDate, timerCount);  
  5.    
  6.     timerCount++;  
  7.     if (timerCount > 3) {  
  8.         [theTimer invalidate];  
  9.     }  
  10. }  


Memory Management

1. The run loop maintains the timer that is registered to it.

2. The timer is passed as an argument when you specify its method as a selector

3. You should maintain a strong reference to the unscheduled timer, in order to ensure that it's not deallocated before you use it.

4. A timer maintains a strong reference to its user info dictionary,

5. A timer maintains a strong reference to its target, so you should make sure that your timer's target survive longer than the timer itself.


Timers的替代方法

如果只是要延迟消息的发送,可以使用NSObject的方法

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait

+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget


创建Timer的三种方法

1.scheduling a timer with the current run loop 

2.creating a timer that you later register with a run loop

3.initializing a timer with a given fire date

Scheduled Timers

以下两个方法自动注册新创建的timer到当前NSRunLoop对象,NSRunLoop的模式为默认的NSDefaultRunLoopMode

  • + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds invocation:(NSInvocation *)invocation repeats:(BOOL)repeats
  • + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats

只发送一次
[plain]  view plain copy print ?
  1. - (IBAction)startOneOffTimer:sender {  
  2.    
  3.     [NSTimer scheduledTimerWithTimeInterval:2.0  
  4.              target:self  
  5.              selector:@selector(targetMethod:)  
  6.              userInfo:[self userInfo]  
  7.              repeats:NO];  
  8. }  


重复发送消息

注:创建重复发送消息的timer一般需要保存一个引用,因为需要在某个时刻停止发送消息

[plain]  view plain copy print ?
  1. - (IBAction)startRepeatingTimer:sender {  
  2.    
  3.     NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5  
  4.                               target:self selector:@selector(timerFireMethod:)  
  5.                               userInfo:[self userInfo] repeats:YES];  
  6.     self.repeatingTimer = timer;  
  7. }  


Unscheduled Timers

创建未注册的timer,使用时调用addTimer:forMode注册到NSRunLoop对象

[plain]  view plain copy print ?
  1. - (IBAction)createUnregisteredTimer:sender {  
  2.    
  3.     NSMethodSignature *methodSignature = [self methodSignatureForSelector:@selector(invocationMethod:)];  
  4.     NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];  
  5.     [invocation setTarget:self];  
  6.     [invocation setSelector:@selector(invocationMethod:)];  
  7.     NSDate *startDate = [NSDate date];  
  8.     [invocation setArgument:&startDate atIndex:2];  
  9.    
  10.     NSTimer *timer = [NSTimer timerWithTimeInterval:0.5 invocation:invocation repeats:YES];  
  11.     self.unregisteredTimer = timer;  
  12. }  

[plain]  view plain copy print ?
  1. - (IBAction)startUnregisteredTimer:sender {  
  2.     if (unregisteredTimer != nil) {  
  3.         NSRunLoop *runLoop = [NSRunLoop currentRunLoop];  
  4.         [runLoop addTimer:unregisteredTimer forMode:NSDefaultRunLoopMode];  
  5.     }  
  6. }  


Initializing a Timer with a Fire Date

创建一个拥有指定发送日期的timer

[plain]  view plain copy print ?
  1. - (IBAction)startFireDateTimer:sender {  
  2.     NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:1.0];  
  3.     NSTimer *timer = [[NSTimer alloc] initWithFireDate:fireDate  
  4.                                       interval:0.5  
  5.                                       target:self  
  6.                                       selector:@selector(countedtargetMethod:)  
  7.                                       userInfo:[self userInfo]  
  8.                                       repeats:YES];  
  9.    
  10.     timerCount = 1;  
  11.     NSRunLoop *runLoop = [NSRunLoop currentRunLoop];  
  12.     [runLoop addTimer:timer forMode:NSDefaultRunLoopMode];  
  13.     [timer release];  
  14. }  

Stopping a Timer

[plain]  view plain copy print ?
  1. - (IBAction)stopRepeatingTimer:sender {  
  2.     [repeatingTimer invalidate];  
  3.     self.repeatingTimer = nil;  
  4. }  
  5.    
[plain]  view plain copy print ?
  1. 也可以从timer发送的消息中停止timer  
[plain]  view plain copy print ?
  1. - (void)countedtargetMethod:(NSTimer*)theTimer {  
  2.    
  3.     NSDate *startDate = [[theTimer userInfo] objectForKey:@"StartDate"];  
  4.     NSLog(@"Timer started on %@; fire count %d", startDate, timerCount);  
  5.    
  6.     timerCount++;  
  7.     if (timerCount > 3) {  
  8.         [theTimer invalidate];  
  9.     }  
  10. }  


Memory Management

1. The run loop maintains the timer that is registered to it.

2. The timer is passed as an argument when you specify its method as a selector

3. You should maintain a strong reference to the unscheduled timer, in order to ensure that it's not deallocated before you use it.

4. A timer maintains a strong reference to its user info dictionary,

5. A timer maintains a strong reference to its target, so you should make sure that your timer's target survive longer than the timer itself.

目录
相关文章
|
6月前
|
缓存 调度 数据库
Python中的定时器用法:Timer定时器和schedule库
Python中的定时器用法:Timer定时器和schedule库
322 0
|
API 调度 Android开发
【Android 异步操作】Timer 定时器 ( Timer 与 TimerTask 基本使用 | Timer 定时器常用用法 | Timer 源码分析 )
【Android 异步操作】Timer 定时器 ( Timer 与 TimerTask 基本使用 | Timer 定时器常用用法 | Timer 源码分析 )
913 0
|
程序员 iOS开发
performSelector的原理以及用法
performSelector的原理以及用法
298 0
|
iOS开发
iOS NSTimer 定时器用法总结
iOS NSTimer 定时器用法总结
254 0
|
C# 数据库 UED
C#之BackgroundWorker从简单入门到深入精通的用法总结
C#之BackgroundWorker从简单入门到深入精通的用法总结需求分析 经常用到的耗时操作,例如: 1、文件下载和上载(包括点对点应用程序传输文件,从网络下载文件、图像等)2、数据库事务(从数据库读到大量的数据到WinForm界面中的DataGridview里呈现)3、复杂的本地计算4、本地磁盘文件访问(读写文件,磁盘文件列表)…… 这些操作在长时间运行时会导致用户界面 (UI) 处于停止响应状态,用户在这操作期间无法进行其他的操作,造成非常差的用户体验,为了不使UI层处于停止响应状态,则可以使用 BackgroundWorker 类方便地解决这类问题。
1312 0
使用NSTimer过程中最大的两个坑
坑1. retain cycle问题。 在一个对象中使用循环执行的nstimer时,若希望在对象的dealloc方法中释放这个nstimer,结局会让你很失望。 这个timer会导致你的对象根本不会被释放,所以不会调用dealloc方法,同时这个nstimer也永远不会停止。
1090 0
|
iOS开发
NSTimer 小记
<p style="font-size:19px; line-height:normal; margin-top:0px; font-family:'Lucida Grande'"> 创建一个 Timer</p> <ul style="margin-left:30px; padding-left:0px; font-family:Verdana,Geneva,Arial,Helveti
1360 0