Why does the timer stop when scrolling in the UIWebView iPhone?

Possible duplicate:
UIScrollView pauses NSTimer until scroll completes

I am having trouble figuring out why NSTimer stops as soon as I view the UIWebView. Please take a look at the following code (I know this is not a home site, but I am honestly stuck):

- (void)viewDidLoad { [super viewDidLoad]; NSString *address = @"http://en.m.wikipedia.org/wiki/"; NSURL *url = [NSURL URLWithString:address]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [wiki loadRequest:request]; time = 0; countValue = 0; timer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target: self selector: @selector(updateTimer) userInfo: nil repeats: YES]; timeRand = 0; countValueRand = 1; randomTimer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target: self selector: @selector(updateRandomTimer) userInfo: nil repeats: YES]; [self generateWordsArray]; } 
+6
source share
2 answers

You need to add a timer to another RunLoopMode. By default, a timer is added to NSDefaultRunLoopMode. This means that the timer only runs when the application launch loop is in NSDefaultRunLoopMode.

Now, when the user touches the screen (for example, to scroll through the UIScrollView), the launch cycle mode switches to NSEventTrackingRunLoopMode. And now that the loop loop is no longer in NSDefaultRunMode, the timer will not execute. The ugly effect is that the timer is locked whenever the user touches the screen. And this may be the time when the user scrolls, as the timer locks until the scroll stops completely. And when the user continues to scroll, the timer locks again.

Fortunately, the solution to this problem is quite simple: you can add your timer to another NSRunLoopMode. When you add a timer to NSRunLoopCommonModes, it will execute in all run cycle modes (which, to be precise, are declared as part of a set of "common" modes). This means that the timer works not only in NSDefaultRunLoopMode, but also in NSEventTrackingRunLoopMode (when the user touches the screen).

So, after initializing the timer, add it to NSRunLoopCommonModes:

 [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; 
+28
source

Well, user interaction blocks the main thread, so the timer is delayed when it adds itself to the current thread execution cycle.

If you want the timer to be called regardless of user interaction, you should consider creating a new thread and linking the timer to that thread.

You can also watch Mike Ashe's GCD based timer , which will run in the background. The only thing you should remember is that user interface updates must be performed in the main thread.

+1
source

Source: https://habr.com/ru/post/892704/


All Articles