IOS NSTimer 定時器

NSTimer 的初始化

初始化方法:有五種初始化方法

  • (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
    //例如:
    //初始化一個Invocation對象
    NSInvocation * invo = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(init)]];
    [invo setTarget:self];
    [invo setSelector:@selector(timerAction)];
    NSTimer * timer = [NSTimer timerWithTimeInterval:1 invocation:invo repeats:YES];
    //加入主循環(huán)池中
    [[NSRunLoop mainRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
    //開始循環(huán)
    [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(timerAction) 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(timerAction:) userInfo:@"123" repeats:YES];
  • (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)repeats:(BOOL)yesOrNo;
    //例如:
    NSTimer * timer = [[NSTimer alloc]initWithFireDate:[NSDate distantPast] interval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];

它的屬性

@property (copy) NSDate *fireDate;//這是設(shè)置定時器的啟動時間,常用來管理定時器的啟動與停止

//啟動定時器
timer.fireDate = [NSDate distantPast];
//停止定時器
timer.fireDate = [NSDate distantFuture];

@property (readonly) NSTimeInterval timeInterval;//這個是一個只讀屬性,獲取定時器調(diào)用間隔時間

@property NSTimeInterval tolerance;//這是7.0之后新增的一個屬性,因為NSTimer并不完全精準(zhǔn),通過這個值設(shè)置誤差范圍

@property (readonly, getter=isValid) BOOL valid;//獲取定時器是否有效

@property (readonly, retain) id userInfo;//獲取參數(shù)信息

釋放,銷毀定時器

[timer invalidate];//是唯一的方法將定時器從循環(huán)池中移除

timer=nil;//同時置空

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容