Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block variables in Objective-C

I have a questions about blocks in Objective-C.

For example I have this code:

__block int count = 0;
void (^someFunction)(void) = ^(void){
count = 4;
};
count +=2;

What would be the proper way to write the same piece of code so the count will become 6, not 2 ?!

Thank you!

I should probably show the actual code because my previous question was blurry. EDIT:

__block CMTime lastTime = CMTimeMake(-1, 1);
    __block int count = 0;
    [_imageGenerator generateCGImagesAsynchronouslyForTimes:stops
                                          completionHandler:^(CMTime requestedTime, CGImageRef image, CMTime actualTime,
                                                              AVAssetImageGeneratorResult result, NSError *error)
     {
         if (result == AVAssetImageGeneratorSucceeded)
         {
             NSImage *myImage = [[NSImage alloc] initWithCGImage:image size:(NSSize){50.0,50.0}];
             [arrOfImages addObject:myImage];
         }

         if (result == AVAssetImageGeneratorFailed)
         {
             NSLog(@"Failed with error: %@", [error localizedDescription]);
         }
         if (result == AVAssetImageGeneratorCancelled)
         {
             NSLog(@"Canceled");
         }
         if (arrOfImages.count > 5)
         {
             NSLog(@"here");
         }
         count++;
     }];
     int f = count+1;

after 10 iterations count is 0...why?!?!

like image 997
Eugene Gordin Avatar asked Jul 20 '26 22:07

Eugene Gordin


1 Answers

You are not executing the block (calling a block someFunctionmight be a misleading thing)

__block int count = 0;
void (^someBlock)(void) = ^{
    count = 4;
};
someBlock();
count +=2;
like image 151
vikingosegundo Avatar answered Jul 23 '26 13:07

vikingosegundo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!