Search code examples
iosobjective-cnstimer

How to properly handle NSTimer calls?


I am running into a situation where I'm not able to properly handle NSTimer.

In my app, I've an option of user chats (I'm not using XMPP because of a low budget project, but the chat is working through API calls ONLY). I've scheduled a timer at a time interval of 15 seconds. If any new chats available I'll get it and will update chat view.

Here's the working scenario:

  1. As this is a UITabbar based app, a user will come to "Chat" tab.
  2. A User will have a list of persons with whom he can chat.
  3. A User will select any of a user – will push to Chat Screen.
  4. Where all locally saved chats will be visible and an API call will be made for new chats, on success (or error) of API call, a timer will be scheduled to sync chats at a time interval of 15 seconds.
  5. If a user goes back (pops), in viewDidDisappear: method, I'm invalidating the (running) timer.

In my Unit testing, if I'll continuously push & pop to/from Chat screen, there'll be multiple instances of that timer will get scheduled. I suspect, this is WRONG.

I'm not sure what I'm doing is correct or not though I need your help to understand the right and the correct way to get my functionality done. I guess here there's no need of the code for above explanation.


Solution

  • First of all, why are you not exploring option of push notification? Polling server every 15 second is a bad design :-(.

    Second, when it comes to NSTimer it is important to start and stop them from the same thread. I would advise you encapsulate your timer start/stop code in below block always ensuring you deal on main thread with your timer.

    dispatch_async(dispatch_get_main_queue(), ^{
    
    });