Executing methods one after another with pauses between executing

后端 未结 2 1774
孤独总比滥情好
孤独总比滥情好 2021-01-03 12:08

Newbie obj-c question. I am writing a simple iPad presentation not for Appstore. My task is to implement few methods executed one after another with little pauses between th

相关标签:
2条回答
  • 2021-01-03 12:20

    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.

    0 讨论(0)
  • 2021-01-03 12:27

    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];
    
    0 讨论(0)
提交回复
热议问题