Chris Liu
Chris Liu

Reputation: 79

NSTimer does not schedule enough times of selector

I am using the following code to update a ui 50 times in 2 seconds which gives 0.04 time interval. However the method updateLabels only gets called 5 or 6 times sometimes far from 50 times. Is this because I block the main thread of anything? Do you guys know how to make it work?

self.timer = [NSTimer timerWithTimeInterval:0.04
                                     target:self                     
                                   selector:@selector(updateLabels)
                                   userInfo:nil 
                                    repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

Upvotes: 0

Views: 55

Answers (1)

bbum
bbum

Reputation: 162722

Just like polling is bad, repeated pushes are bad, too.

As @rmaddy said, go read the docs on timers and how they work.

Instead, I'd suggest:

  • mark the time
  • do an update
  • when update is done, check time elapsed
  • if > than update interval, do an update
  • if < than update interval, do a delayed update

Keep in mind that the above is probably not quite what you want, either. If you are updating UIKit views, then the updates might be coalesced and drawing might happen on a background thread. I.e. when the update calculation is done, the screen might not be fully painted.

As well, you really don't want to be doing updates N times a second unless the data is really changing that quickly. If it is changing that quickly, then look at CADisplayLink and architect your code to target a particular frames per second update rate. If it isn't changing that quickly, then only update when the data changes; redrawing the same thing is a waste of battery life.

Upvotes: 2

Related Questions