设为首页 加入收藏

TOP

NSTimer 定时器总结(一)
2017-10-13 10:23:01 】 浏览:5228
Tags:NSTimer 定时器 总结

一、初始化方法:有五种初始化方法,分别是

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;

使用方法:

- (void)viewDidLoad {

    [super viewDidLoad];

    //初始化一个Invocation对象

    NSInvocation * invo = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(init)]];

    [invo setTarget:self];

    [invo setSelector:@selector(myLog)];

    NSTimer * timer = [NSTimer timerWithTimeInterval:1 invocation:invo repeats:YES];

    //加入主循环池中

    [[NSRunLoop mainRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];

    //开始循环

    [timer fire];

}

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;

使用方法:

NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 invocation:invo repeats:YES];

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

使用方法:

NSTimer * timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(myLog) userInfo:nil repeats:NO]

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

使用方法:

NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(myLog:) userInfo:@"123" repeats:YES]

- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep 

使用方法:

NSTimer * timer = [[NSTimer alloc]initWithFireDate:[NSDate distantPast] interval:1 target:self selector:@selector(myLog:) userInfo:nil repeats:YES];

[[NSRunLoop mainRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];

注意:这五种初始化方法的异同:

        1、参数repeats是指定是否循环执行,YES将循环,NO将只执行一次。

        2、timerWithTimeInterval这两个类方法创建出来的对象如果不用 addTimer: forMode方法手动加入主循环池中,将不会循环执行。并且如果不手动调用fair,则定时器不会启动。

        3、scheduledTimerWithTimeInterval这两个方法不需要手动调用fair,会自动执行,并且自动加入主循环池。

        4、init方法需要手动加入循环池,它会在设定的启动时间启动。

二、成员变量

@property (copy) NSDate *fireDate;

这是设置定时器的启动时间,常用来管理定时器的启动与停止

    //启动定时器

    timer.fireDate = [NSDate distantPast];

    //停止定时器

    timer.fireDate = [NSDate distantFuture];

@property (readonly) NSTim

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇swift学习笔记2——函数、闭包 下一篇iOS之获取经纬度并通过反向地理编..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目