Hibernia Hibernia - 1 year ago 67
iOS Question

How taxing would running an NSTimer every second be?

I've got a tableview of information that is locked/unlocked based on timestamps.

If I've got cell A B and C and they unlock in 30 seconds, 1 min, and 1min 30 respectively based on timestamps pulled from Firebase, I need a way to check those timestamps to unlock them, aka enable them being able to select the cell.

The only way I can think of doing this is to set up a NSTimer that runs every second to check against an array of a Post Class which would have a timestamp attribute and a locked attribute. When the view loads I'd check the timestamp and initially set the locked attribute based on the timestamp, and then the NSTimer will run every second and compare the posts timestamp to its "unlock" date. If a post is ready to unlock its "locked" variable will switch off to "false" and the user will be able to click into it.

Because I'm showing what's locked/unlocked with an image on the cell as well this would require a reload on the tableview every second to keep the locked image up to date. This sounds awful.

Is there a good way to do this or would doing it this way be okay?

Answer Source

Several thoughts:

  1. The tableview would not need to reload every second based on the scenario you described. You would be checking every second the timer fires but it would only need to be reloaded when the posts in question actually need to be unlocked (seems like that is roughly at 30 second intervals, not that bad at all).

  2. If you can figure out the index of the cells that need to be reloaded, you can just call the reloadRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) UITableView method directly. This would avoid updating the entire tableview to reload a single row and can improve UX a little bit if you are experiencing jumpiness due to rows reloading too much. Documentation here

  3. If you are concerned about the actual timer firing every second but know that you have a finite number of rows (particularly if it is just 3 as you listed), then you can just create a separate timer for each row that fires at the appropriate time (30 seconds, 1 minute, etc). However, a single timer firing every second is not that big of a deal and shouldn't cause any noticeable performance issues.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download