iOS中定时器NSTimer的使用

1、初始化

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

注:不用scheduled方式初始化的,需要手动addTimer:forMode: 将timer添加到一个runloop中。

  而scheduled的初始化方法将以默认mode直接添加到当前的runloop中.

举例:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];

NSTimer *myTimer = [NSTimer  timerWithTimeInterval:3.0 target:selfselector:@selector(timerFired:)userInfo:nilrepeats:NO];

[[NSRunLoop  currentRunLoop] addTimer:myTimerforMode:NSDefaultRunLoopMode];

2、触发(启动)

当定时器创建完(不用scheduled的,添加到runloop中后,该定时器将在初始化时指定的timeInterval秒后自动触发。

可以使用-(void)fire;方法来立即触发该定时器;

注:You can use this method to fire a repeating timer without interrupting its regular firing schedule. If the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived.

在重复执行的定时器中调用此方法后立即触发该定时器,但不会中断其之前的执行计划;

在不重复执行的定时器中调用此方法,立即触发后,就会使这个定时器失效。

3、停止

- (void)invalidate;

这个是唯一一个可以将计时器从runloop中移出的方法。

注:

NSTimer可以精确到50-100毫秒.

NSTimer不是绝对准确的,而且中间耗时或阻塞错过下一个点,那么下一个点就pass过去了.

延时函数和Timer的使用

//延时函数:
[NSThread sleepForTimeInterval:5.0]; //暂停5s. //Timer的使用:
NSTimer *connectionTimer; //timer对象 //实例化timer
self.connectionTimer=[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop]addTimer:self.connectionTimer forMode:NSDefaultRunLoopMode];
//用timer作为延时的一种方法
do{
[[NSRunLoopcurrentRunLoop]runUntilDate:[NSDatedateWithTimeIntervalSinceNow:1.0]];
}while(!done); //timer调用函数
-(void)timerFired:(NSTimer *)timer{
done =YES;
}

转自:http://magicalboy.com/objective_c_nstimer_usage/#comment-45

创建 NSTimer

    1. Scheduled Timers & Using Selector
- (IBAction)startOneOffTimer:sender {
 
    [NSTimer scheduledTimerWithTimeInterval:2.0
 
             target:self
 
             selector:@selector(targetMethod:)
 
             userInfo:[self userInfo]
 
             repeats:NO];
 
}
      如上,如果没有重复执行的timer相当于

[self performSelector:@selector(targetMethod:) withObject:nil afterDelay:2.0];

// declcare
@property (assign) NSTimer *repeatingTimer;
 
// implements
- (IBAction)startRepeatingTimer:sender {
 
 
 
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5
 
                              target:self selector:@selector(timerFireMethod:)
 
                              userInfo:[self userInfo] repeats:YES];
 
    self.repeatingTimer = timer;
 
}
 
- (IBAction)stopRepeatingTimer:sender {
 
    [repeatingTimer invalidate];
 
    self.repeatingTimer = nil;
 
}
    1. Unscheduled Timers & Using Invocation
// declare
@property (retain) NSTimer *unregisteredTimer;
 
 
 
// implements
- (IBAction)createUnregisteredTimer:sender {
 
    NSMethodSignature *methodSignature = [self methodSignatureForSelector:@selector(invocationMethod:)];
 
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
 
    [invocation setTarget:self];
 
    [invocation setSelector:@selector(invocationMethod:)];
 
    NSDate *startDate = [NSDate date];
 
    [invocation setArgument:&startDate atIndex:2];
 
 
    NSTimer *timer = [NSTimer timerWithTimeInterval:0.5 invocation:invocation repeats:YES];
 
    self.unregisteredTimer = timer;
 
}
 
 
 
- (IBAction)startUnregisteredTimer:sender {
 
    if (unregisteredTimer != nil) {
 
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
 
        [runLoop addTimer:unregisteredTimer forMode:NSDefaultRunLoopMode];
 
    }
 
}
 
- (IBAction)stopUnregisteredTimer:sender {
 
    [unregisteredTimer invalidate];
 
    self.unregisteredTimer = nil;
 
}

定时器(NSTimer)的更多相关文章

  1. 定时器NSTimer的用法

        //时间间隔     NSTimeInterval activeTimeInterval = NETWORK_SEND_ACTIVE_TIME;     NSTimeInterval othe ...

  2. [置顶] ios 时间定时器 NSTimer应用demo

    原创文章,转载请注明出处:http://blog.csdn.net/donny_zhang/article/details/9251917 demo功能:ios NSTimer应用demo .ipho ...

  3. iOS定时器-- NSTimer 和CADisplaylink

    iOS定时器-- NSTimer 和CADisplaylink 一.iOS中有两种不同的定时器: 1.  NSTimer(时间间隔可以任意设定,最小0.1ms)// If seconds is les ...

  4. ios基础篇(二十三)—— 定时器NSTimer与图片的自动切换

    一.NSTimer NSTimer是一个能在从现在开始到后面的某一个时刻或者周期性的执行我们指定的方法的对象.可以按照一定的时间间隔,将制定的信息发送给目标对象.并更新某个对象的行为.你可以选择在未来 ...

  5. IOS中定时器NSTimer的开启与关闭

    调用一次计时器方法: myTimer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(scro ...

  6. ios - 图片自动轮播定时器(NSTimer)以及消息循环模式简介

    本文只是演示如何设置图片轮播的定时器. 创建全局变量NSTimer 程序启动后就开始轮播图片,所以在- (void)viewDidLoad中就启动定时器. 将定时器放入消息循环池中.- (void)v ...

  7. 定时器 NSTimer 和 CADisplayLink

    NSTimer *timer; CADisplayLink *caDisplayLink; int timeCount; - (void)viewDidLoad { [super viewDidLoa ...

  8. iOS定时器NSTimer的使用方法

    1.初始化 + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelect ...

  9. 【转】IOS中定时器NSTimer的开启与关闭

    原文网址:http://blog.csdn.net/enuola/article/details/8099461 调用一次计时器方法: myTimer = [NSTimer scheduledTime ...

随机推荐

  1. 决策树-预测隐形眼镜类型 (ID3算法,C4.5算法,CART算法,GINI指数,剪枝,随机森林)

    1. 1.问题的引入 2.一个实例 3.基本概念 4.ID3 5.C4.5 6.CART 7.随机森林 2. 我们应该设计什么的算法,使得计算机对贷款申请人员的申请信息自动进行分类,以决定能否贷款? ...

  2. HDU 5384 字典树、AC自动机

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=5384 用字典树.AC自动机两种做法都可以做 #include<stdio.h> #includ ...

  3. 5分钟教你Windows 10中将“运行”固定到开始菜单

    导读 “运行”功能深受很多资深IT之家用户喜爱,因为它简约.方便.实用.在Win7等旧版系统中,用户可以让该功能直接在开始菜单显示,方便操作.但在Win10中,由于开始菜单已经重新编写,原有的设定已经 ...

  4. lintcode 75 Find Peak Element

    Hi 大家,这道题是lintcode上的find peak element的题,不是leecode的那道, 这两道题是有区别的,这道题的题目中说明了:只有左右两侧的数都小于某个元素,这种才是峰值, 而 ...

  5. SQL手册

    来自 W3School 的 SQL 快速参考.可以打印它,以备日常使用. SQL 语句 语句 语法 AND / OR SELECT column_name(s)FROM table_nameWHERE ...

  6. Python自动化之线程进阶篇

    拓展知识 什么是CPU-bound(计算密集型) 和I/O bound(I/O密集型) ? I/O bound 指的是系统的CPU效能相对硬盘/内存的效能要好很多,此时,系统运作,大部分的状况是 CP ...

  7. 浅谈python的import

    动态加载模块: 使用__import__ c=__import__('sys') 等价于 import sys 不过前者可以在执行时决定. 静态加载: 也就是常规的import from xxx im ...

  8. 使用Gitosis搭建Git服务器

    使用Gitosis搭建Git服务器 作者: JeremyWei | 可以转载, 但必须以超链接形式标明文章原始出处和作者信息及版权声明 网址: http://weizhifeng.net/build- ...

  9. KVC 与 KVO 理解

    KVC 与 KVO 是 Objective C 的关键概念,个人认为必须理解的东西,下面是实例讲解. Key-Value Coding (KVC) KVC,即是指 NSKeyValueCoding,一 ...

  10. 自动化监控利器-Zabbix

    转自: http://www.xuliangwei.com/xubusi/117.html   1.1为何需要监控系统 在一个IT环境中会存在各种各样的设备,例如:硬件设备.软件设备.其系统的构成也是 ...