定时器在多线程中的使用

时间:2014-05-31 16:59:33   收藏:0   阅读:285

在多线程中使用定时器必须开启Runloop,因为只有开启Runloop保持现成为活动状态,才能保持定时器不断执行

bubuko.com,布布扣
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self performSelectorInBackground:@selector(testMultiThread) withObject:nil];
}
- (void) testMultiThread {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
    // 1 - 用这种方式创建的定时器,会被自动加入到Runloop中
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];    
    
    // 2 -用这种方式创建的定时器,不会被自动加入到Runloop中,需要手动加入
    //NSTimer * timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    // 3 -  将定时器加入Runloop中
    //[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    
    
    //开启Runloop来使线程保持存活状态
    [[NSRunLoop currentRunLoop] run];
    
    [pool release];
    
    NSLog(@"线程结束");
}

- (void) timeAction {
    NSLog(@"%s",__FUNCTION__);
}
bubuko.com,布布扣

 

 

定时器在多线程中的使用,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!