對這幾個也算不上有很深的理解,只是平時用到些許timer,thread。
想起有次去baidu筆試遇到runloop和timer等的區別,當時就不會。
兩三月過去了,如今終於稍微整理了下。
有不對的地方盼指正。
(版權所有哦)
· NSThread:常見的線程
每個進程裏都有多個線程,我們一般如下實用thread:
[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];
如果函數需要輸入參數,那麼可以從object傳進去。你也可以這樣實現
NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(myThreadMainMethod:) object:nil];
[myThread start]; // Actually create the thread
(from apple: threading PG)
你的對象也可以直接使用線程:
[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];
· NSTimer:定時器
等待一定時間後,觸發某個事件發生,可循環觸發。默認是添加到當前runloop。你也可以添加到自己新建的runloop裏去,注意如果添加的話runloop會retain timer,你應當release timer而將timer交給runloop,就像將operation加入operationQueue中一樣。
可以很簡單的調用:
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(addLabel) userInfo:nil repeats:YES];
- (void)addLabel
{
label.text = [NSString stringWithFormat:@"%d",num++];
}
每隔2秒,就觸發定時器,向self發送addLabel消息。
· NSRunLoop
當有輸入信號(input source,比如鍵盤鼠標的操作、),NSPort和NSConnection對象時,runloop提供了一個程序接口,即等待輸入。但是我們從來都不需要去創建或者去管理一個runloop。在每個進程中都相應的有runloop,不管時當前的主進程還是你新建的進程。如果需要訪問當前進程的runloop可以調用類方法:+ (NSRunLoop *)currentRunLoop。
[[NSRunLoop currentRunLoop] performSelector:@selector(addLabel2)
target:self
argument:nil
order:0
modes:[NSArray arrayWithObjects:@"NSDefaultRunLoopMode",nil]]
//舉個例子而已,一般不會這樣用
一般需要使用runloop也就是對於netservice,stream等對象以某種模式schedule在當前的runloop,如:
[[_session inputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];。
Runloop的作用在於當有事情要做時它使當前的thread工作,沒有事情做時又使thread 休眠sleep。注意Runloop並不是由系統自動控制的,尤其是對那些你新建的次線程你需要對其進行顯示的控制。
Runloop顧名思義就是一個不停的循環,不斷的去check輸入,如下圖。
我們需要了解runloop modes這對判斷事件來源以及添加到runloop時很有必要。
正如之前我們所說,只有創建了次線程才需要我們管理runloop,但是也並不是創建了次線程就一定需要管理runloop,僅當:
o Use ports or custom input sources to communicate with other threads.
o Use timers on the thread.
o Use any of the performSelector... methods in a Cocoa application.
o Keep the thread around to perform periodic tasks.
你還可以註冊runloop,這樣可以使用kvo。
· NSTask:
使用task你可以運行其它程序作爲當前程序的子進程,並監控它的運行。它和線程的不同之處在於它並不何創建它的進程(父進程)共享內存。可以說是“完全”獨立的一個東西。