(转)在新线程中使用NSTimer
(转)在新线程中使用NSTimer
转自:NStimer 在滚动ScrollView的时候停止,在新线程中使用NSTimer
1 方法一: 2 3 -(void) viewDidLoad{ 4 [self performSelectorInBackground:@selector(call1) withObject:nil]; 5 } 6 7 -(void) call1{ 8 timer1 = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(doSomething) userInfo:nil repeats:NO]; 9 10 [[NSRunLoop currentRunLoop] addTimer:timer1 forMode:NSRunLoopCommonModes]; 11 12 } 13 14 -(void) call2{ 15 // do something 16 timer1 invalidate]; 17 timer1 = nil; 18 } 19 20 方法二: 21 22 - (void)viewDidAppear:(BOOL)animated { 23 NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(timerStart) object:nil]; 24 [timerThread start]; 25 } 26 27 -(void)timerStart 28 { 29 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 30 NSRunLoop* runLoop = [NSRunLoop currentRunLoop]; 31 timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(method) userInfo:nil repeats:YES] retain];//一定要retain,不然timerStart执行完后,NSTimer就被释放了。 32 [runLoop run]; 33 [pool release]; 34 } 35 36 - (void)viewDidDisappear:(BOOL)animated { 37 [super viewDidDisappear:animated]; 38 [timer invalidate]; 39 } 40 41 方法三: 42 43 timer = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(SendHeartBeat) userInfo:nil repeats:YES]; 44 45 [[NSRunLoop mainRunLoop] addTimer:heartTimer forMode:NSDefaultRunLoopMode];
浙公网安备 33010602011771号