NSRunLoop 典型用法

来源:互联网 发布:冷库机组的简易算法 编辑:程序博客网 时间:2024/05/30 04:14

-(void)backgroundThreadStarted {

  NSAutoreleasePool* thePool = [[NSAutoreleasePool alloc] init];

  // create a scheduled timer

  NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(backgroundThreadFire:) userInfo:nil repeats:YES];

  [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

  m_isBackgroundThreadToTerminate = NO;

  // create the runloop

  double resolution = 300.0;

  BOOL isRunning;

  do {

    // run the loop!

    NSDate* theNextDate = [NSDate dateWithTimeIntervalSinceNow:resolution]; 

    isRunning = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:theNextDate]; 

    // occasionally re-create the autorelease pool whilst program is running

    [thePool release];

    thePool = [[NSAutoreleasePool alloc] init];            

  } while(isRunning==YES && m_isBackgroundThreadToTerminate==NO);

  

  [thePool release];

}

-(void)backgroundThreadFire:(id)sender {

  // do repeated work every one second here

  // when thread is to terminate, call [self backgroundThreadTerminate];

}

-(void)backgroundThreadTerminate {

  m_isBackgroundThreadToTerminate = YES;

  CFRunLoopStop([[NSRunLoop currentRunLoop] getCFRunLoop]);

}

原创粉丝点击