是什么?
@interface NSTimer : NSObject
在經過一定時間間隔后觸發的計時器,可將指定的消息發送到目標對象。
使用定時器
+scheduledTimerWithTimeInterval:taget:selector:userInfo:repeasts:
"ti" - 每隔多少秒,觸發計時器
"target" - 調用"哪個類"的方法。
"selector" - "什么方法"(也就是做什么事情). 如果傳參,傳遞的是計時器對象本身.
如: "timerFireMethod:"
- (void)timerFireMethod:(NSTimer *)timer
"userInfo" - 計時器的用戶信息.可以為 nil。
"repeats" - YES,重復調用,直到計時器銷毀。NO,計時器將在其觸發后失效。
返回新的"NSTimer對象"
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti
target:(id)aTarget
selector:(SEL)aSelector
userInfo:(id)userInfo
repeats:(BOOL)yesOrNo;
舉例 - 1
假設: self 是 ViewController.
每隔"2秒"調用一次"當前類的timerScroll方法",一直循環調用.
(在ViewController里面沒有找到timerScroll方法,則報錯)
[NSTimer scheduledTimerWithTimeInterval: 2.0 target:self selector: @selector(timerScroll) userInfo:nil repeats:YES];
-- 未找到"timerScroll"方法
reason: '-[ViewController timerScroll]: unrecognized selector sent to instance 0x7fc22bd4b1f0'
舉例 - 2
[NSTimer scheduledTimerWithTimeInterval: 2.0 target:self selector: @selector(timerScroll:) userInfo:@"用戶信息" repeats:NO];
-(void)timerScroll:(NSTimer *)timer{
NSLog(@"userInfo =%@, timer = %@",timer.userInfo,timer);
}
"效果如下:"
userInfo =用戶信息, timer = <__NSCFTimer: 0x600003f62d00>
"說明: "
1. "userInfo" 就像發信息,那邊發什么信息,這里就接收什么信息.
2. "repeats:NO" 說明"NSTimer"只運行一次!
3. "timerScroll :" 傳遞的是"NSTimer"本身.
block - 方式使用NSTimer
+scheduledTimerWithTimeInterval: repeats:block:
"interval" - 時間間隔
"repeats" - 是否重復
"block" - 需要定時運行的 "代碼"
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval
repeats:(BOOL)repeats
block:(void (^)(NSTimer *timer))block;
舉例 - 1
"每隔2秒,調用timerScroll方法"
[NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
[self timerScroll];
}];
銷毀定時器
-(void)stopTimer{
[self.timer invalidate];
self.timer = nil; "strong修飾的Timer,需要將指針清空.避免出現野指針問題"
}
NSTimer 使用strong
修飾還是weak
修飾呢? 為什么?
- 一般來說,OC對象用
strong
來修飾.控件用weak
來修飾. -
NSTimer
是OC對象,應該來說是用strong
修飾. - 但是,有這么一個情況:
NSTimer
可以獨立的運行.不需要self.timer = [NSTimer ....]
來強指針指向.
如:[NSTimer scheduledTimerWithTimeInterval:2.0 ....]
這樣寫,NSTimer
照常工作.這說明一直都有個強指針指向NSTimer
.所以定時器不會被銷毀. - 所以根據,能用
weak
就不用strong
的原則, NSTimer 最好使用weak來修飾. - 因為
weak
修飾的對象一旦被銷毀,則全部銷毀. 不會有歷史遺留問題而引的野指針. - 用
weak
來修飾NSTimer
,上面示例中可以省去self.timer = nil;
.