Skip to content

Instantly share code, notes, and snippets.

@SheldonWangRJT
Last active May 19, 2023 19:06
Show Gist options
  • Save SheldonWangRJT/0cb2997e51ba96bcee97fc4edd6e68dc to your computer and use it in GitHub Desktop.
Save SheldonWangRJT/0cb2997e51ba96bcee97fc4edd6e68dc to your computer and use it in GitHub Desktop.
Shat is the difference among sleep() , usleep() & [NSThread sleepForTimeInterval:]?

#iOSBySheldon #objective-c #swift #unitTest #uiTest #sleep

This notes is written by Sheldon. You can find me with #iOSBySheldon in Github, Youtube, Facebook, etc.

The only reason that I wrote this short quick note is that, the answers on the internet is somewhat misleading.

If we are running sleep() usleep() or [NSThread sleepForTimeInterval:] in your main app, there should not be any difference. Because the first two functions are just functions that from c and the third one is from objective-c.

However,

  • You probably should NOT call them in your main app, because for delay operations you should more use (in Swift) swift DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: { // Put your code which should be executed with a delay here })
  • If you are using these functions in tests (Unit test & UI automation Test), they are slightly different. In my observation, calling sleep() will pause the operation (tap, swipe), [NSThread sleepForTimeInterval:] will likely pause the app execution.

Summary

Trying all of the three in your code, specially in testing classes, if one is not working. They are not quite same.

@1rlan
Copy link

1rlan commented May 19, 2023

gde otveeet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment