天天看点

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