NSTimer 简述

来源:互联网 发布:java项目遇到最大困难 编辑:程序博客网 时间:2024/05/21 04:20

日常开发中,我们经常会使用到NSTimer,看是简单但有复杂!
举例下面使用NSTimer 使用出现的问题

NSThread *Thread =  [[NSThread alloc]initWithTarget:self selector:@selector(threed) object:nil];    [Thread start];-(void)threed{    NSThread *red= [NSThread currentThread];    if ([red isMainThread]) {        NSLog(@"MainThread");    }else    {        NSLog(@"NotMainThread");    }  NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(test ) userInfo:nil repeats:YES];}-(void)test{NSLog(@"run");{//会发现timer执行了, scheduledTimerWithTimeInterval 这个方法在子线程不跑了,如果想要他执行怎么办?需要引用另一个方法:timerWithTimeInterval 把上面的换成下面这样: NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(test ) userInfo:nil repeats:YES];[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];    [[NSRunLoop currentRunLoop] run];     这样就可以在子线运行了!

scheduledTimerWithTimeInterval,这个方法是自动回放入到默认的runloop中,除了主线程之外,其他线程的NSRunloop只有在调用[NSRunloop currentRunloop]才会创建。如有不对 请指点 !

1 0
原创粉丝点击