문제

I got stuck in a problem. I'm trying to run a timer in a method which itself is in background resulting my timer is not initiating. I got to know some where that timer can't be initialized in background so is there any way to do this?

도움이 되었습니까?

해결책

You can perform the operation on main thread.

[self performSelectorOnMainThread:@selector(initTimer) withObject:nil waitUntilDone:NO];

and then

- (void)initTimer {
// Init your timer here.
}

다른 팁

You can try Background Fetch in ios7 to run code on background

Try this :

// provide value as required. Time here is 3 sec
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC); 

dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    // do your task
});

As pointed out by @Bryan Chen, you can schedule a method to be run on the current thread using the following code:

dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC);
dispatch_after(when, dispatch_get_current_queue(), ^(void) {
    [self myTimedMethod];
});

You cannot use NSTimer in a background thread unless you are maintaining a run loop on that thread.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top