分享

在新线程中使用NSTimer

 最初九月雪 2016-03-22

方法一:

-(void) viewDidLoad{
[self performSelectorInBackground:@selector(call1) withObject:nil];
}

-(void) call1{
timer1 = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(doSomething) userInfo:nil repeats:NO];

[[NSRunLoop currentRunLoop] addTimer:timer1 forMode:NSRunLoopCommonModes];

}

-(void) call2{
// do something
timer1 invalidate];
timer1 = nil;
}

方法二:

- (void)viewDidAppear:(BOOL)animated {
   
NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(timerStart) object:nil];
   
[timerThread start];
}

-(void)timerStart
{
   
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
    timer
= [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(method) userInfo:nil repeats:YES] retain];//一定要retain,不然timerStart执行完后,NSTimer就被释放了。
   
[runLoop run];
   
[pool release];
}

- (void)viewDidDisappear:(BOOL)animated {
   
[super viewDidDisappear:animated];
   
[timer invalidate];
}
方法三:
timer = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(SendHeartBeat) userInfo:nil repeats:YES];
 [[NSRunLoop mainRunLoop] addTimer:heartTimer forMode:NSDefaultRunLoopMode];

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多