码迷,mamicode.com
首页 > 其他好文 > 详细

NSThread 详解

时间:2014-05-15 20:34:41      阅读:305      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   tar   

第一、iOS主线程专门用来更新显示UI界面、处理用户触摸事件的,所以不能阻塞主线程,否则带来极坏的用户体验。

一般的解决方案就是将那些耗时的操作放到另外一个线程中去执行。

    NSThread *red=[NSThread currentThread]; //获取当前线程

NSThread *mainThread=[NSThread mainThread]; //获取主线程

        [red setName:@"hello"];   //设置线程名称
        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];

        [_thread start];

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

线程交互sample:

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



NSThread 详解,布布扣,bubuko.com

NSThread 详解

标签:style   blog   class   code   c   tar   

原文地址:http://blog.csdn.net/richard_rufeng/article/details/25886483

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!