Christian Gossain
Christian Gossain

Reputation: 5972

How can I delay method calls?

I want to be able to call a method and then, either wait for the method to finish doing it's thing and then invoke the next method call, OR call a method, wait a certain amount of time and then invoke the next method.

Any thoughts on how I would do that?

Example:

[self method1];
//wait for method1 to finish whatever it's doing then move onto the next line
[self method2];

OR

[self method1];
//wait say, 500ms then move onto the next line
[self method2];

Upvotes: 0

Views: 363

Answers (3)

hotpaw2
hotpaw2

Reputation: 70733

Break your code in half (e.g. into multiple methods).

    ...
    [self method1];
    return;
}

- (void) secondHalf {
    [self method2];
    ...

To wait for method1 to finish, exit/quit/return from your 1st part of your code back to the run loop. Have something else start the latter half of your method (notification, delegation, timer, etc.). Save any needed local variables or other state in instance variables.

Upvotes: 0

Joseph Tura
Joseph Tura

Reputation: 6360

If you want to make sure that method has finished doing what it does, why not either

a) call method2 at the end of method1

or

b) go with performSelectorOnMainThread:withObject:waitUntilDone: as suggested by Deniz Mert Edincik

or

c) Send an NSNotification at the end of method1 to trigger method2 (you could add an observer for that notification in method1 and remove it again in method2, if method1 is also called elsewhere and you do not want method2 triggered every time)

You should not work with afterDelay, relying on whatever delay you specify...

Upvotes: 1

Related Questions