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.

目录
相关文章
|
NoSQL Java Redis
springboot搭建后台框架 (二)整合Redis
springboot搭建后台框架 (二)整合Redis
144 0
|
人工智能
虚拟键盘AI
本文提供了一个虚拟键盘AI项目的详细代码实现,包括链接摄像头、手势识别、绘制键盘、确定选中字母以及使用`pynput`库模拟真实键盘输入的步骤,并附有环境配置指南。
虚拟键盘AI
|
C语言
C语言之给定n个数据, 求最大值出现的位置(如果最大值出现多次,求出第一次出现的位置即可,位置从1开始)。
C语言之给定n个数据, 求最大值出现的位置(如果最大值出现多次,求出第一次出现的位置即可,位置从1开始)。
470 0
|
区块链 Windows 存储
icon 制作
引用:http://apps.hi.baidu.com/share/detail/30039475 ico是Icon file的缩写,是Windows的图标文件格式的一种,可以存储单个图案、多尺寸、多色板的图标文件。
1183 0
|
8月前
|
数据采集 人工智能 自然语言处理
代理IP:人工智能时代的助力与挑战
在数字化时代,人工智能(AI)和代理IP正逐渐改变我们的生活与工作方式。AI通过模拟人类智能,在图像、语音识别等领域取得显著成果;代理IP则通过隐藏真实IP地址保护隐私、突破网络限制。两者结合,为未来创新带来无限可能。代理IP作为中间服务器,隐藏用户身份,提升数据采集效率,保障模型训练安全,优化网络连接,突破地域限制,助力智能客服、电商物流、AI图像生成等应用。尽管面临稳定性和隐私挑战,但其与AI的融合发展前景广阔,将为生活带来更多便利与创新。
128 1
|
网络协议 安全 物联网
IPv4 与 IPv6: 理解它们的基本区别
IPv4 与 IPv6: 理解它们的基本区别
3812 0
|
机器学习/深度学习 人工智能 自然语言处理
自动化办公:AI如何改变工作方式
【7月更文第19天】随着人工智能技术的飞速发展,我们的工作方式正经历着前所未有的转型。从繁琐的文档处理到高效的会议安排,再到个性化的邮件回复,AI正逐步成为现代办公不可或缺的一部分。本文将深入探讨AI如何在这些核心办公场景中发挥作用,提升工作效率,优化工作流程,从而推动工作方式的全面革新。
1253 3
|
存储 SQL 缓存
C++解释器模式实战:从设计到应用的全面指南
C++解释器模式实战:从设计到应用的全面指南
404 0
|
机器学习/深度学习 人工智能 算法
【人工智能】人工智能的历史发展与机器学习和神经网络
【人工智能】人工智能的历史发展与机器学习和神经网络
251 0
|
前端开发 Java 数据库连接
源码解析最流行的Validator框架——Hibernate Validator
源码解析最流行的Validator框架——Hibernate Validator
860 0
源码解析最流行的Validator框架——Hibernate Validator

热门文章

最新文章