I need to add delay between the execution of two lines in a(same) function. Is there is any favorable options to do this?
Note: I don't need two different functions to do this, and the delay must not affect other functions' execution.
eg:
line 1: [executing first operation];
line 2: Delay /* I need to introduce delay here */
line 3: [executing second operation];
Any help is appreciable. Thanks in advance...
You can use the
NSThread
method:However, if you do this on the main thread you'll block the app, so only do this on a background thread.
or in Swift
in Swift 3
You can use gcd to do this without having to create another method
You should still ask yourself "do I really need to add a delay" as it can often complicate code and cause race conditions
This line calls the selector secondMethod after 3 seconds:
Use it on your second operation with your desired delay. If you have a lot of code, place it in its own method and call that method with
performSelector:
. It wont block the UI likesleep
Edit: If you do not want a second method you could add a category to be able to use blocks with performSelector:
Or perhaps even cleaner:
If you're targeting iOS 4.0+, you can do the following:
I have a couple of turn-based games where I need the AI to pause before taking its turn (and between steps in its turn). I'm sure there are other, more useful, situations where a delay is the best solution. In Swift:
I just came back here to see if the Objective-C calls were different.(I need to add this to that one, too.)
Like @Sunkas wrote,
performSelector:withObject:afterDelay:
is the pendant to thedispatch_after
just that it is shorter and you have the normalobjective-c
syntax. If you need to pass arguments to the block you want to delay, you can just pass them through the parameterwithObject
and you will receive it in theselector
you call:If you still want to choose yourself if you execute it on the main thread or on the current thread, there are specific methods which allow you to specify this. Apples Documentation tells this: