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. Ubuntu 14 如何打开 .chm格式文档?

    好多手册是.chm格式,Ubuntu是需要安装第三方软件才能打开.chm格式文档,操作方式如下: 到“软件中心” -> 搜索“xchm”,并安装 -> 右键某个.chm文档,选择“属性” ...

  2. Js控制iFrame切换加载网址

    <html> <head> <title>Js控制 iFrame 切换加载网址</title> </head> <body> & ...

  3. android 4种启动模式

    在android里,有4种activity的启动模式,分别为: “standard” (默认) “singleTop” “singleTask” “singleInstance” 它们主要有如下不同: ...

  4. tomcat 虚拟节点

    <Context path=”Welcome” docBase=”c:\hello\hello” reloadable=”true” /> contex指上下文,实际上就是一个web项目: ...

  5. CSS Reset样式重置

    为了让页面在各不同浏览器之间显示效果一致,CSS样式清除和重置是前端开发必需要做的事情,结合前车之鉴,整理了份CSS重置样式代码供参考. @charset "utf-8"; /* ...

  6. qt-5.6.0 移植之qt源码编译

    其实这只是给自己看的一个configure选项笔记,没有太多的东西. 首先: 下载qt5.6的源码: 地址: http://download.qt.io/archive/qt/5.6/ 下载完解压: ...

  7. GPS坐标互转:WGS-84(GPS)、GCJ-02(Google地图)、BD-09(百度地图)

    WGS-84:是国际标准,GPS坐标(Google Earth使用.或者GPS模块)GCJ-02:中国坐标偏移标准,Google Map.高德.腾讯使用BD-09:百度坐标偏移标准,Baidu Map ...

  8. django xadmin多个model的数据渲染在统一个template中

    adminx.py demo class ModelAdmin(object): #.... def get_context(self): context = super(SimCardService ...

  9. 更换CentOS7的下载源为阿里云

    安装epel rpm -ivh http://mirrors.ustc.edu.cn/fedora/epel/7/x86_64/e/epel-release-7-7.noarch.rpm 1.备份 m ...

  10. mysql备份与还原

    一.直接拷贝数据库文件 直接拷贝数据库文件一般是使用文件系统备份工具cp,适合小型数据库,是最可靠的. 当你拷贝数据库文件时,必须保证表没有正在使用.如果服务器在你拷贝一个表的时候改变这个表,拷贝就失 ...