首页 > 代码库 > NSThread 详解
NSThread 详解
第一、iOS主线程专门用来更新显示UI界面、处理用户触摸事件的,所以不能阻塞主线程,否则带来极坏的用户体验。
一般的解决方案就是将那些耗时的操作放到另外一个线程中去执行。
NSThread *red=[NSThread currentThread]; //获取当前线程
NSThread *mainThread=[NSThread mainThread]; //获取主线程
if ([red isMainThread]) { //判断当前线程是否是主线程
NSLog(@"currentThread:%@",red);
}
第二、NSThread的创建
1. - (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
参数的意义: selector :线程执行的方法,这个selector只能有一个参数,而且不能有返回值。
target :selector消息发送的对象
argument:传输给target的唯一参数,也可以是nil
sample:
NSThread *thread=[[NSThread alloc] initWithTarget:self selector:@selector(timerThread) object:nil];
[thread start];
-(void)timerThread
{
NSTimer *timer=[NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(timeSchedule) userInfo:nil repeats:YES];
NSRunLoop *runLoop=[NSRunLoop currentRunLoop];
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
while ([runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
}
-(void)timeSchedule
{
num++;
NSLog(@"now the number is %d",num);
}
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];
[_threadstart];
[selfperformSelector:@selector(lastResult)onThread:_threadwithObject:nilwaitUntilDone:YES];
线程交互sample:
http://download.csdn.net/detail/ycxmartin111111/7351381