今天突然才之間才意識到NSTimer這樣的運行方式,是在多線程中實現的迴圈還是在主線程中去實現的呢。當然不可能是在主線程中的while那麼簡單,那樣什麼都幹不了,簡單看了下NSTimer是以同步方式啟動並執行。時間到了,訊息發出後,ontimer的函數是在主線程上調用的。
我們會經常看到這樣的代碼:
- - (IBAction)start:(id)sender
- {
- pageStillLoading = YES;
- [NSThread detachNewThreadSelector:@selector(loadPageInBackground:)toTarget:self withObject:nil];
- [progress setHidden:NO];
- while (pageStillLoading) {
- [NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
- }
- [progress setHidden:YES];
- }
複製代碼
這段代碼很神奇的,因為他會“暫停”代碼運行,而且程式運行不會因為這裡有一個while迴圈而受到影響。在[progress setHidden:NO]執行之後,整個函數想暫停了一樣停在迴圈裡面,等loadPageInBackground裡面的操作都完成了以後才讓[progress
setHidden:YES]運行。這樣做就顯得簡介,而且邏輯很清晰。如果你不這樣做,你就需要在loadPageInBackground裡面表示load完成的地方調用[progress setHidden:YES],顯得代碼不緊湊而且容易出錯。
[iGoogle有話說:應用程式架構主線程已經封裝了對NSRunLoop
runMode:beforeDate:的調用;它和while迴圈構成了一個訊息泵,不斷擷取和處理訊息;可能大家會比較奇怪,既然主線程中已經封裝好了對NSRunLoop的調用,為什麼這裡還可以再次調用,這個就是它與Windows訊息迴圈的區別,它可以嵌套調用.當再次調用while+NSRunLoop時候程式並沒有停止執行,它還在不停提取訊息/處理訊息.這一點與Symbian中Active Scheduler的嵌套調用達到同步作用原理是一樣的.]
記錄一篇文章:http://www.cocoachina.com/bbs/read.php?tid-38499.html
還有一個使用的例子:
-(void)backgroundThreadStarted {
NSAutoreleasePool* thePool = [[NSAutoreleasePool alloc] init];
// create a scheduled timer
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(backgroundThreadFire:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
m_isBackgroundThreadToTerminate = NO;
// create the runloop
double resolution = 300.0;
BOOL isRunning;
do {
// run the loop!
NSDate* theNextDate = [NSDate dateWithTimeIntervalSinceNow:resolution];
isRunning = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopModebeforeDate:theNextDate];
// occasionally re-create the autorelease pool whilst program is running
[thePool release];
thePool = [[NSAutoreleasePool alloc] init];
} while(isRunning==YES && m_isBackgroundThreadToTerminate==NO);
[thePool release];
}
-(void)backgroundThreadFire:(id)sender {
// do repeated work every one second here
// when thread is to terminate, call [self backgroundThreadTerminate];
}
-(void)backgroundThreadTerminate {
m_isBackgroundThreadToTerminate = YES;
CFRunLoopStop([[NSRunLoop currentRunLoop] getCFRunLoop]);
}