Executing methods one after another with pauses between executing

笑着哭i 提交于 2019-11-30 16:23:07
Fogmeister

You could add these to an NSOperation queue...

NSOperationQueue *queue = [NSOperationQueue new];

queue.maxConcurrentOperationCount = 1;

[queue  addOperationWithBlock:^{
    [self method1];
}];

[queue  addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:2.0];
    [self method2];
}];

[queue  addOperationWithBlock:^{
    [NSThread sleepForTimeInterval:2.0];
    [self method3];
}];

...

This will then run each one only after the previous one has finished and put the 2 second delay in for you.

Careful about using this to do an UI stuff though. This will run in a Background thread so you may need to deal with that.

Maybe this might work better you could do it by subclassing NSOperation but that's a lot of work for not much benefit.

Run this from where ever you want, I suggest putting all this into a function called setUpQueue or something.

Then from viewWillAppear or viewDidLoad or somewhere else, on a button press, etc... do...

[self setUpQueue];

All you have to do is add stuff to the queue, the queue will then manage itself.

You could use the single timer and write a switch statement around the methods you want to execute in the order you want to execute them. e.g.

int turn = 0;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(runmethod) userInfo:nil repeats:NO];

then in run method

switch(turn)
{
  case 0:
        // do method 1 stuff
        ++turn;
        break;
  case 1:
        // do method 2 stuff
        ++turn;
        break;
    .
    .
    .
}

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(runmethod) userInfo:nil repeats:NO];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!