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. java依赖注入

    接口的作用 1.在spide中创建一个私有接口 private Downloadable downlaodable 覆盖set get 方法 创建一个方法  Public Page down load ...

  2. 在lua脚本中使用我们自定义的精灵类

    首先创建cocos2dx-lua项目,然后在项目中添加我们的自定义精灵类:这里Himi类名为:HSprite // // HSprite.h // cocos2dx_lua_tests_by_Himi ...

  3. 【PHP面向对象(OOP)编程入门教程】11.类的继承

    继承作为面向对象的三个重要特性的一个方面,在面向对象的领域有着及其重要的作用,好像没听说哪个面向对象的语言不支持继承. 继承是PHP5面象对象程序设计的重要特性之一,它是指建立一个新的派生类,从一个或 ...

  4. C++ 传参数 拉起程序

    ShellExecute(NULL,_T("open"),_T("Update.exe"),"Own",NULL,SW_HIDE);

  5. CSS3圆角边框的使用-遁地龙卷风

    0.快速入门 border-radius:50px; 1.border-radius详解 border-radius:50px; 上右下左,水平和垂直距离都是50px border-radius:50 ...

  6. Android界面刷新之invalidate与postInvalidate的区别

    Android的invalidate与postInvalidate都是用来刷新界面的. 在UI主线程中,用invalidate():本质是调用View的onDraw()绘制. 主线程之外,用postI ...

  7. ClearCanvas DICOM 开发系列 一

    概述 C#开源的DICOM server.支持影像处理.影像归档.影像管理.影像传输和影像浏览功能.开源代码可学习地方很多. 官方网站:http://www.clearcanvas.ca buildi ...

  8. uploadify插件的功能应用

    一.相关key值介绍 uploader:uploadify.swf文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后淡出打开文件对话框,默认值:uploadify.swf. scri ...

  9. 分布式架构 Hadoop 2.7.X 安装和配置

    一.安装环境 硬件:虚拟机 操作系统:Ubuntu 14 32位 IP:59.77.132.28主机名:admin安装用户:root 二.安装JDK 安装JDK1.7或者以上版本.这里安装jdk1.7 ...

  10. phpcms评论框iframe无法自适应问题

    问题背景: 之前用友言的时候改过网站的ip地址,改成127开头的了.但是协同开发的时候别人用的还是localhost. 结果在用评论的时候iframe死活不能自适应,看了一下源代码v9本身已经写过if ...