標籤

2012年4月15日 星期日

performSelectorInBackground 的用途

簡單點說,就是另開一個BACKGROUND THREAD來運行performSelectorInBackground指定的 METHOD。

EXTRA:
在处理过程中一个单独的线程,使用 performSelectorInBackground 的代码更新可可的界面
http://d2100.com/questions/12858

OTHER
http://www.d2100.com/questions/43422
http://songyee.com/category/tech/objective-c/

關於performSelectorInBackground不會在MAIN THREAD運作
http://stackoverflow.com/questions/3694120/performselectorinbackground-on-main-thread

P.S.
要詳細理解,可下載APPLE SAMPLE CODE﹣IPHONEMixerEQGraphTest.
開入面個CONSOLE睇下,你會發現兩邊的MAIN THREAD同背景THREAD的PRINTF不停交錯,經常SWITCH THREAD。從而証明同步(OR異步?)運作。
https://discussions.apple.com/thread/1964587?start=0&tstart=0


- (IBAction)doStuff:(id)sender {
 [self.indicator startAnimating]; // ok, start activity indicator before spawn
 // a new thread.
 [self performSelectorInBackground:@selector(doInBackground) withObject:nil];
}

- (void)doInBackground {
 NSAutoreleasePool * pool;
 pool = [[NSAutoreleasePool alloc] init];
 [self doLengthyProcessing]; //I am putting some image processing code here
//just for the test. Since 'doInBackground' is running in background thread, any
//function calls inside 'doInBackground' should run in the background thread,
//and should return before 'doInBackground' does, am I wrong?

 [self performSelectorOnMainThread:@selector(stopIndicator) withObject:nil waitUntilDone:NO];
 [pool drain];
}

- (void)stopIndicator {
 [self.activityIndicator stopAnimating];
}

- (void)doLengthyProcessing {
 // ...
}

沒有留言:

張貼留言