在Objective-C中阻止变量

Eug*_*din 1 objective-c objective-c-blocks

我对Objective-C中的块有疑问.

例如,我有这个代码:

__block int count = 0;
void (^someFunction)(void) = ^(void){
count = 4;
};
count +=2;
Run Code Online (Sandbox Code Playgroud)

编写同一段代码的正确方法是什么,所以计数将变为6而不是2?

谢谢!

我应该展示实际代码,因为我之前的问题很模糊.编辑:

__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;
Run Code Online (Sandbox Code Playgroud)

10次​​迭代后计数为0 ......为什么?!?!

Vik*_*ica 6

你没有执行块(调用块someFunction可能是一个误导性的事情)

__block int count = 0;
void (^someBlock)(void) = ^{
    count = 4;
};
someBlock();
count +=2;
Run Code Online (Sandbox Code Playgroud)


MAN*_*rii 5

像这样调用块:

someFunction();
Run Code Online (Sandbox Code Playgroud)

那就是:

__block int count = 0;
void (^someFunction)(void) = ^(void){
    count = 4;
};
// call block
someFunction();

count +=2;
Run Code Online (Sandbox Code Playgroud)