开发者

How can I delay method calls?

开发者 https://www.devze.com 2023-01-22 23:31 出处:网络
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 ti

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];


with : performSelector:withObject:afterDelay:


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消