Search code examples
iphoneobjective-ciosblock

Implement a mechanism for chaining messages in Objective-C?


I'm writing an app which requires running a method after another method completes. (Common scenario, right?)

I'm trying to implement chained methods. The best I've come up with is to call performSelector:withObject:afterDelay:. I'm simply not sure if that is the best way to do this. I've looked into how the Cocos2d game engine implements its CCSequence class, but I'm not sure I understand it.

I suspect blocks would do well here, except I'm not sure how to use them as callback objects or whatever.

How would I implement a mechanism for running methods, one after the other? (I'm open to using timers or blocks, but I don't know how I'd use blocks in this case.)

Edit:

To clarify, I'm trying to implement a system like cocos2d's CCSequence class, which takes a few methods and "dispatches" them in sequence. Things like animations, which take much more than a single clock cycle to run.

I'm not looking to block the main thread, nor do I want to hard code methods to each other. Cocos2d has a sequencing system where I can pass in methods to a queue and run them sequentially.

Edit 2:

Also, I'd like to be able to cancel my scheduled queues, and so I'm not sure GCD is a good match for this. Can GCD serial queues be canceled?


Solution

  • I finally found what I'm looking for. Completion blocks. Simply put, I'd write a method like this:

    - (void) performSomeActionWithCompletion:(void (^)()) completion{
    
         [self someAction];
    
         if(completion()){
           completion(); 
         }
    
    }
    

    Now I can call my method like so:

    [self performSomeActionWithCompletion:^{
      NSLog(@"All done! (Well, not the async stuff, but at any rate...)");
    }];