場景A
- 調(diào)用一次計(jì)時(shí)器方法
//不重復(fù),只調(diào)用一次。timer運(yùn)行一次就會(huì)自動(dòng)停止運(yùn)行
[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(scrollTimer) userInfo:nil repeats:NO];
- 重復(fù)調(diào)用計(jì)時(shí)器方法
//每1秒運(yùn)行一次function方法。
timer =
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(function:) userInfo:nil repeats:YES];
注意:將計(jì)數(shù)器的repeats設(shè)置為YES的時(shí)候,self的引用計(jì)數(shù)會(huì)加1。因此可能會(huì)導(dǎo)致self(即viewController)不能release,所以,必須在dealloc的時(shí)候,將計(jì)數(shù)器timer停止,否則可能會(huì)導(dǎo)致內(nèi)存泄露。
- 取消定時(shí)器
停止timer的運(yùn)行,但這個(gè)是永久的停止:(注意:停止后,一定要將timer賦空,否則還是沒有釋放。不信?你自己試試~)
//取消定時(shí)器
[timer invalidate];
timer = nil;
場景B
要想實(shí)現(xiàn):先停止,然后再某種情況下再次開啟運(yùn)行timer,可以使用下面的方法:
首先關(guān)閉定時(shí)器不能使用上面的方法,應(yīng)該使用下面的方法:
- 暫停定時(shí)器
[myTimer setFireDate:[NSDate distantFuture]];
- 繼續(xù)定時(shí)器
[myTimer setFireDate:[NSDate distantPast]];
場景C
例子:比如,在頁面消失的時(shí)候關(guān)閉定時(shí)器,然后等頁面再次打開的時(shí)候,又開啟定時(shí)器。
(主要是為了防止它在后臺(tái)運(yùn)行,暫用CPU)可以使用下面的代碼實(shí)現(xiàn):
//頁面將要進(jìn)入前臺(tái),開啟定時(shí)器
-(void)viewWillAppear:(BOOL)animated
{
//開啟定時(shí)器
[scrollView.myTimer setFireDate:[NSDate distantPast]];
}
//頁面消失,進(jìn)入后臺(tái)不顯示該頁面,關(guān)閉定時(shí)器
-(void)viewDidDisappear:(BOOL)animated
{
//關(guān)閉定時(shí)器
[scrollView.myTimer setFireDate:[NSDate distantFuture]];
}
場景D
NSTimer和UIScrollView的用法
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300)];
[self.view addSubview:scrollView];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(method:) userInfo:nil repeats:YES];
//修改當(dāng)前runloop的mode為NSRunLoopCommonModes
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
NSDefaultRunLoopMode 默認(rèn)模式
UITrackingRunLoopMode 拖動(dòng)默認(rèn)(一般用在滾動(dòng)視圖)
NSRunLoopCommonModes 可配置的一組模式