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,
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
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,
- void (^playComeAndRead)(BOOL) = ^(BOOL finished) {
- double delayInSeconds = 0.3;
- dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
- dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
- if (_audioPlayer) {
- _audioPlayer = nil;
- }
- audioString=@"Come And Read";
- _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
- [_audioPlayer play];
- });
- };
- for (UIView *subview in [self.view subviews]) {
- if (subview.tag != 0 && subview.tag !=102) {
- reMOVE
- isFound = YES;
- [UIView transitionWithView:self.view duration:1.580 options:UIViewAnimationOptionTransitionCurlUp
- animations:^ {
- [self.view addSubview:_readScrollView];
- }
- completion: playComeAndRead
- ];
- }
- }
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,
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
Post a Comment