iOS: Using blocks as a variable

If you're into iOS programming and has a background on other programming languages like Java, Javascript, PHP, or Python, these languages have their own style of defining lambda or closures which you can assign to a specific variable and then call that variable as a method or function per se.

I just wanted to take notes on this so I might not forget, and well share this with you. Below is a snippet part of the game I wrote which looks like this,


  1.    void (^playComeAndRead)(BOOL)  = ^(BOOL finished) {
  2.        double delayInSeconds = 0.3;
  3.        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
  4.        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
  5.            if (_audioPlayer) {
  6.                _audioPlayer = nil;
  7.            }
  8.           
  9.            audioString=@"Come And Read";
  10.            audioURL = [[NSBundle mainBundle] URLForResource:audioString withExtension:@"mp3"];
  11.            NSError *error;
  12.            _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
  13.            [_audioPlayer play];
  14.        });
  15.    };
  16.   
  17.    for (UIView *subview in [self.view subviews]) {
  18.        if (subview.tag != 0 && subview.tag !=102) {
  19.            reMOVE
  20.            isFound = YES;
  21.            [UIView transitionWithView:self.view duration:1.580 options:UIViewAnimationOptionTransitionCurlUp
  22.                    animations:^ {
  23.                        [self.view addSubview:_readScrollView];
  24.                    }
  25.                    completion: playComeAndRead
  26.            ];
  27.        }
  28.    }



As you can see, from line 1, I have called and used it on line 25.

If you have some variabled to be added inside a block (a closure), be sure to declare that this variable is under the scope of __block.

Example,

__block int x = 123; //

Some articles or sites are helpful to look at,
http://agilewarrior.wordpress.com/2012/05/11/how-to-pass-blocks-as-variables-in-objective-c/

but the best is to look at Apple's Developer Manual,
http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/Blocks/Articles/bxVariables.html

Comments

Popular posts from this blog

Converting sectors into MB - Useful in understanding the sectors in iostat in Linux

What is Disk Contention?

Installing MySQL from source: Could NOT find Curses (missing: CURSES_LIBRARY CURSES_INCLUDE_PATH)