2013-08-31 31 views

回答

7

这些属性添加到您的.h文件中

@property (nonatomic, strong) NSTimer *updateTimer; 
@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask; 

现在,假设你有一个按钮动作 - > btnStartClicked 那么你的方法是这样的:

-(IBAction)btnStartClicked:(UIButton *)sender { 
    self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 
                 target:self 
                 selector:@selector(calculateNextNumber) 
                 userInfo:nil 
                 repeats:YES]; 
    self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 
     NSLog(@"Background handler called. Not running background tasks anymore."); 
     [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask]; 
     self.backgroundTask = UIBackgroundTaskInvalid; 
    }]; 

} 

-(void)calculateNextNumber{ 
    @autoreleasepool { 
     // this will be executed no matter app is in foreground or background 
    } 
} 

,如果您需要停止使用此方法,

- (IBAction)btnStopClicked:(UIButton *)sender { 

    [self.updateTimer invalidate]; 
    self.updateTimer = nil; 
    if (self.backgroundTask != UIBackgroundTaskInvalid) 
    { 
     [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask]; 
     self.backgroundTask = UIBackgroundTaskInvalid; 
    } 
    i = 0; 
} 
相关问题