我在用Interface Builder設計的GUI編寫Cocoa應用程序。我需要在不阻塞UI調度後臺活動(定期),所以我在一個單獨的線程中運行它,就像這樣:在不同的NSThread/NSRunLoop中運行和管理NSTimer
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[self performSelectorInBackground:@selector(schedule) withObject:nil];
}
- (void) schedule {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
timer = [[NSTimer scheduledTimerWithTimeInterval:FEED_UPDATE_INTERVAL
target:activityObj
selector:@selector(run:)
userInfo:nil
repeats:YES]
retain];
[runLoop run];
[pool release];
}
我保留了計時器,所以我可以很容易地無效並重新安排。
問題:爲響應GUI事件,我還必須觸發run:方法,因此它是同步的(即「執行活動」按鈕)。像這樣:
[timer fire];
我也可以用performSelectorInBackground來做到這一點,當然也不會阻塞UI。但是這個同步發射在另一個runloop中運行!所以我不能保證它們不會重疊。我怎樣才能將所有的發射排列在同一個runloop上?