【问题标题】:In Objective-C (or C), how does this code with pointer to a bool work?在 Objective-C(或 C)中,这个带有 bool 指针的代码是如何工作的?
【发布时间】:2021-01-23 03:03:24
【问题描述】:

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;
};

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

这里到底发生了什么?

【问题讨论】:

    标签: c objective-c pointers primitive


    【解决方案1】:

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

    【讨论】:

    • 知道了,谢谢。我以错误的方式思考它。该块一遍又一遍地运行并不断分配给*stop。它没有发生任何神奇的突变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 2010-12-13
    • 2013-07-24
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多