繁体   English   中英

在 Objective-C(或 C)中,这个带有布尔指针的代码如何工作?

[英]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的值更改并且块将*stop设置为该值之后调用了该块。

捕获*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在闭包之外不存在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM