在 Objective-C(或 C)中,带有指向 bool 的指针的这段代码如何工作?

In Objective-C (or C), how does this code with pointer to a bool work?

stop 机制在这段代码中是如何工作的?

@interface GifAnaimator()
@property BOOL stopping;
@end

@implementation GifAnaimator
- (void)startWithURL:(CFURLRef)imageURL {
    __weak GifAnaimator *weakSelf = self;
    CGAnimateImageAtURLWithBlock(imageURL, nil, ^(size_t index, CGImageRef image, bool* stop) {
        // Some image handling code...
        *stop = weakSelf.stopping;
    });
}

- (void)stop {
    self.stopping = YES;
}
@end

这段代码让我感到困惑的是,取消引用的 stop 被分配了一个普通的、未指向的 BOOLstopping。之后,当 stopping 发生变异时,stop 以某种方式得到相同的变异。

我尝试在一个块中捕获 stop,然后调用该块以像这样对其进行变异:

weakSelf.stopAnimation = ^{
   *stop = YES;
};

这段代码对我来说更有意义,但它不起作用。

这里到底发生了什么?

CGAnimateImageAtURLWithBlock 的文档注释说:

/* Animate the sequence of images contained in the file at `url'. Currently supported image
 * formats are GIF and APNG. The `options' dictionary may be used to request additional playback
 * options; see the list of keys above for more information. The block is called on the main queue
 * at time intervals specified by the `delay time' of the image. The animation can be stopped by
 * setting the boolean parameter of the block to false.
 */

如果 self.stopping 发生突变并且 *stop 稍后获得相同的突变,我认为这是因为在更改 self.stopping 的值并且块设置 [=15] 之后调用该块=] 到那个值。

捕获 *stop 将不起作用,因为很可能它不存在于块之外。

NSDictionary 有一个具有类似签名的方法:

- (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts 
                                usingBlock:(void (^)(KeyType key, ObjectType obj, BOOL *stop))block

在伪代码中,它会做类似的事情:

for (key, object) in storage {
    BOOL stop = NO;
    block(key, object, &stop);
    if(stop) {
        break;
    }
}

所以 stop 在闭包之外不存在。