NSThread 详解

第一、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);
}

<span style="font-family: SimSun; font-size: 18px; background-color: rgb(255, 255, 255);">2.隐式创建线程</span>

[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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值