views:

7009

answers:

3

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?

+17  A: 

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.)

smorgan
+4  A: 

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
+12  A: 

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
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.
Algorithmic
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
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 Simmons
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