[英]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
被分配了一个普通的、非指向的BOOL
、 stopping
。 之后,当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.