122

In Java you can suspend the current thread's execution for an amount of time using Thread.sleep(). Is there something like this in Objective-C?

Cœur
  • 37,241
  • 25
  • 195
  • 267
levi
  • 2,035
  • 3
  • 16
  • 11

6 Answers6

164

Yes, there's +[NSThread sleepForTimeInterval:]

(Just so you know for future questions, Objective-C is the language itself; the library of objects (one of them at least) is Cocoa.)

Pang
  • 9,564
  • 146
  • 81
  • 122
smorgan
  • 20,228
  • 3
  • 47
  • 55
  • 8
    Thnx!
    for future reference, the definition is actually +[NSThread sleepForTimeInterval:] (so, used like [NSThread sleepForTimeInterval:0.1]).
    – TinkerTank Dec 07 '10 at 18:00
  • This is perfect. Thanks! I just finished up my animation blocks and it worked like a charm. – RileyE Nov 14 '12 at 03:03
  • how about sleeping on main therad? – stackunderflow Dec 12 '12 at 06:29
  • 1
    It's the same; the main thread is just a thread. Sleeping on the main thread is usually a bad idea though, since it makes your program non-responsive. – smorgan Dec 17 '12 at 09:42
  • 4
    for those wondering, [NSThread sleepForTimeInteval: ] is the same as [[NSThread currentThread] sleepForTimeInterval: ]. – pnizzle Aug 31 '14 at 23:40
111

Sleeping for one second in Java:

Thread.sleep(1000);

Sleeping for one second in Objective C:

[NSThread sleepForTimeInterval:1.0f];
Rok Strniša
  • 6,781
  • 6
  • 41
  • 53
41

Why are you sleeping? When you sleep, you are blocking the UI and also any background URL loading not in other threads (using the NSURL asynchronous methods still operates on the current thread).

Chances are what you really want is performSelector:withObject:AfterDelay. That's a method on NSObject you can use to call a method at some pre-determined interval later - it schedules a call that will be performed at a later time, but all of the other stuff the thread handles (like UI and data loads) will still continue.

Kendall Helmstetter Gelner
  • 74,769
  • 26
  • 128
  • 150
  • 44
    Sleeping is useful to me for testing purposes. I can simulate some network delays to make sure that my app responds properly. Currently I'm testing against a local web server, so everything is essentially instantaneous. – brantonb Feb 24 '10 at 02:26
  • 7
    Sleep is the wrong way to test network delays. Look at the answer for this question http://stackoverflow.com/questions/1502060/iphone-intermittent-network-testing to see how to test variable speeds of networks in the simulator. Because sleeping the main thread blocks up everything, you are not simulating a network delay at all, but more of a suspension of the app. – Kendall Helmstetter Gelner Aug 03 '10 at 05:07
  • Sleeping is useful to simulate what is done on a join operation on a JAVA thread. You sleep for 10 millis, check if the thread is dead then you can dealloc it. – Mike S Sep 20 '10 at 06:45
  • 1
    If you sleep for any period of time your thread will be exactly in the same state as it was before you slept. It's not a good test because in the real world your application will be processing, not sleeping. That's why it's important to figure out how to test without relying on sleep. – Kendall Helmstetter Gelner Sep 20 '10 at 20:17
  • +1 Thanks for pointing out an alternative solution! Just what I was looking for :) – jpswain Oct 05 '11 at 16:02
  • No, just the thread you are calling sleepForTimeInterval on. It's an instance method of a single Thread instance. – Kendall Helmstetter Gelner Nov 05 '12 at 00:06
  • Sleeping is good for me for certain animations that don't respond to delays. Throw it in an asynchronous block and you're good to go. – RileyE Nov 14 '12 at 03:01
  • It doesn't matter if you put it in a block, it operates on whatever thread the block is run within. If you are blocking animations you are probably also totally losing any UI response to the user. – Kendall Helmstetter Gelner Nov 14 '12 at 04:48
  • Thread sleep is the WORST POSSIBLE WAY to simulate heavy work, because it's shutting down a thread and giving the processor more time to work on other things!!!!! I cannot emphasize enough what a terrible awful idea it is to use sleep to simulate heavy work... if you want to simulate heavy work you use blocks doing repeated needless computation, not give the processor a milk run by setting a whole thread to sleep!!! – Kendall Helmstetter Gelner Aug 20 '13 at 05:58
  • It really depends on what you're testing. In my case, I just need to interactively simulate a slowly-loading webservice call. There's no need to simulate CPU usage. The various alternatives to sleeping described here are overkill for my purposes. – Andrew Rondeau Oct 30 '13 at 19:58
  • It does NOT depend on what you are testing. Using sleep() in NO WAY simulates a slowly loading web service call - in fact it is the worst possible thing you could do to test that scenario since the thread you are on will be hung INSTEAD of working on other tasks as it would normally during a slow web service call, you will be masking all kinds of potential issues and to your running code it will look like your call was instantly completed instead of being slow. Use the Network Link Conditioner tool (Mac) to test slow calls. – Kendall Helmstetter Gelner Oct 30 '13 at 20:33
  • Hmm, quite a debate, let me throw in my 2 cents: admittedly sleeping a thread is by far not simulating heavy work, but it does depend on the perspective. If you want to test a server's reaction to heavy load, `sleep()` is useless indeed. But, if you want to test the client's reaction to the server being slow, you can use `sleep()` on the server, as far as the client is concerned it's the exact same thing (plus, it's way easier to implement and understand). – Teodor Sandu Apr 24 '14 at 07:17
  • I'll grant sleep() on the server is as you say identical to the server taking a long time to process a request, I was more saying it's not the same as transmission from the server taking a long time to reach you - which has a different effect on the client. – Kendall Helmstetter Gelner Apr 24 '14 at 21:04
  • I use sleep to test an external event occurring while my app is in the middle of processing something in the background. The background processing takes sub-second; and so I put a sleep between the start and end of the processing, so that I can easily trigger the external event in the middle. If there's a better way to test this without sleep, I'd like to know! – Eric D'Souza May 18 '15 at 17:58
  • I'm sleeping because I'm trying to find the source of a one-frame animation glitch, and the delay let's me figure out whether the glitch is happening before or after a certain block of code. – Wowfunhappy Dec 27 '20 at 19:35
9

Of course, you could also use the standard Unix sleep() and usleep() calls, too. (If writing Cocoa, I'd stay with the [NSThread sleepForTimeInterval:], however.)

Bill Heyman
  • 211
  • 1
  • 4
6

If you use NSThread sleepForTimeInterval(commented code) to sleep, fetching data will be blocked, but +[NSThread sleepForTimeInterval:] (checkLoad method) will not block fetching data.

My example code as below:

- (void)viewDidAppear:(BOOL)animated
{
//....
//show loader view
[HUD showUIBlockingIndicatorWithText:@"Fetching JSON data"];
//    while (_loans == nil || _loans.count == 0)
//    {
//        [NSThread sleepForTimeInterval:1.0f];
//        [self reloadLoansFormApi];
//        NSLog(@"sleep ");
//    }
[self performSelector:@selector(checkLoad) withObject:self afterDelay:1.0f];
}

-(void) checkLoad
{
    [self reloadLoansFormApi];
    if (_loans == nil || _loans.count == 0)
    {
        [self performSelector:@selector(checkLoad) withObject:self afterDelay:1.0f];
    } else
    {
        NSLog(@"size %d", _loans.count);
        [self.tableView reloadData];
        //hide the loader view
        [HUD hideUIBlockingIndicator];
    }
}
wu liang
  • 1,993
  • 18
  • 12
0

usleep() can also be used as ive used this to pause the current thread at times

j2emanue
  • 60,549
  • 65
  • 286
  • 456