iPhone-SDK:Call a function in the background?

前端 未结 3 618
野的像风
野的像风 2020-12-09 00:12

Is it possible to call my function in the background after certain interval programmatically in iPhone SDK development? I want to call one particular function in the backgro

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 01:10

    Easiest way is to schedule a NSTimer on the main threads run-loop. I suggest that the following code is implemented on your application delegate, and that you call setupTimer from applicationDidFinishLaunching:.

    -(void)setupTimer;
    {
      NSTimer* timer = [NSTimer timerWithTimeInterval:10 * 60
                                               target:self
                                             selector:@selector(triggerTimer:)
                                             userInfo:nil
                                              repeats:YES];
      [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    }
    
    -(void)triggerTimer:(NSTimer*)timer;
    {
      // Do your stuff
    }
    

    If your stuff here takes a long time, and you can not hold up the main thread then either call your stuff using:

    [self performSelectorInBackground:@selector(myStuff) withObject:nil];
    

    Or you could run the NSTimer on a background thread by with something like this (I am intentionally leaking the thread object):

    -(void)startTimerThread;
    {
      NSThread* thread = [[NSThread alloc] initWithTarget:self
                                                 selector:@selector(setupTimerThread)
                                               withObject:nil];
      [thread start];
    }
    
    -(void)setupTimerThread;
    {
      NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
      NSTimer* timer = [NSTimer timerWithTimeInterval:10 * 60
                                               target:self
                                             selector:@selector(triggerTimer:)
                                             userInfo:nil
                                              repeats:YES];
      NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
      [runLoop addTimer:timer forModes:NSRunLoopCommonModes];
      [runLoop run];
      [pool release];
    }
    
    -(void)triggerTimer:(NSTimer*)timer;
    {
      // Do your stuff
    }
    

提交回复
热议问题