天天看點

NSThread 詳解

第一、iOS主線程專門用來更新顯示UI界面、處理使用者觸摸事件的,是以不能阻塞主線程,否則帶來極壞的使用者體驗。

一般的解決方案就是将那些耗時的操作放到另外一個線程中去執行。

    NSThread *red=[NSThread currentThread]; //擷取目前線程

NSThread *mainThread=[NSThread mainThread]; //擷取主線程

        [red setName:@"hello"];   //設定線程名稱

        if ([red isMainThread]) {  //判斷目前線程是否是主線程

            NSLog(@"currentThread:%@",red);

        }

 第二、NSThread的建立

參數的意義: 

selector :線程執行的方法,這個selector隻能有一個參數,而且不能有傳回值。 

target  :selector消息發送的對象 

argument:傳輸給target的唯一參數,也可以是nil

sample:

2.隐式建立線程

[self performSelectorInBackground:@selector(timerThread) withObject:nil];

會隐式地建立一條新線程,并且在這條線程上調用self的timerThread方法

3.detachNewThreadSelector 建立線程

 [NSThread detachNewThreadSelector:@selector(timerThread) toTarget:self withObject:nil];

4. 停止目前線程的執行

[NSThread exit];

5. 暫停目前線程幾秒

  [NSThread sleepForTimeInterval:4];

6. 在主線程上執行

 [self performSelectorOnMainThread:@selector(lastResult) withObject:nil waitUntilDone:YES];

7.在指定線程上執行操作

_thread=[[NSThreadalloc]

initWithTarget:selfselector:@selector(timerThread)object:nil];

        [_thread

start];

        [selfperformSelector:@selector(lastResult)onThread:_threadwithObject:nilwaitUntilDone:YES];

線程互動sample:

http://download.csdn.net/detail/ycxmartin111111/7351381

上一篇: cms
下一篇: .subversion