IOS開發—NSTimer
建立timer對象的三種方法
一、這兩個類方法建立一個timer並把它指定到一個預設的runloop模式中+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;二、這兩個類方法建立一個timer的對象,不把它指定到哪個runloop. (當建立之後,你必須手動的調用NSRunLoop下對應的方法 addTimer:forMode: 去將它指定到一個runloop模式中.)+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;三、建立一個NSTimer的執行個體 (當建立之後,你必須手動的調用NSRunLoop下對應的方法 addTimer:forMode: 去將它指定到一個runloop模式中.)- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep-
通常使用
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;TimeInterval:時間間隔,浮點型的值。小於0時系統預設為0.1。用於指定沒間隔該時間段觸發一次指定的方法target:方法作用對象 比如self selector:作用方法userInfo:當定時器失效時,由你指定的對象保留和釋放該定時器。通常為nilrepeats:YES時,不斷迴圈直至計時器失效或被釋放。NO時只迴圈一次就失效
其餘方法介紹
- (void)fire;立即觸發計時器- (void)invalidate;停止計時並使觸發器失效- (BOOL)isValid;判斷觸發器是否有效- (NSTimeInterval)timeInterval;觸發間隔時間- (id)userInfo;一般為nil- (NSDate *)fireDate;//開始時間- (void)setFireDate:(NSDate *)date;//設定fireData,其實暫停、開始會用到
定時器暫停與開始的簡要寫法
[timer setFireDate:[NSDate distantPast]];//開啟[timer setFireDate:[NSDate date]]; //繼續。[timer setFireDate:[NSDate distantFuture]];//暫停暫停之後計時器仍然有效,而如果用invalidate則會失效
在invalidate之前最好先用isValid先判斷是否還線上程中
if ([timer isValid] == YES) { [timer invalidate]; timer = nil;}