【发布时间】:2026-01-06 01:05:02
【问题描述】:
假设我有一个类似下面的函数,每秒调用 30 次(这段代码是我试图理解的由 Apple 创建的更复杂代码的简化。Apple 原始代码的想法是这样的:就像我说的 doSomethingWithImage 每秒调用 30 次。所以,整个方法有 1/30 秒的时间来做所有事情,但想象一下 doSomethingThatWillTakeTime 花费的时间比预期的要多,doSomethingWithImage 被再次调用,而 doSomethingThatWillTakeTime 是已经被执行。如果是这种情况,代码必须删除该图像并且什么都不做。
// code...
@synchronized (self);
[self doSomethingWithImage:image];
}
// ...
// call under @synchronized( self )
- (void)doSomethingWithImage:(UIImage *)image
{
self.myImage = image;
[self executeBlockAsync:^{
UIImage *myImage = nil;
@synchronized( self )
{
myImage = self.myImage;
if (myImage) {
self.myImage = nil; // drop the image
}
}
if ( myImage ) {
[self doSomethingThatWillTakeTime:myImage];
}
}];
}
(void)executeBlockAsync:(dispatch_block_t)block
{
dispatch_async( _myQueue, ^{
callbackBlock();
} );
}
我的问题是看这段代码我看不出它是如何做到的。我不知道正在执行哪些行以使其发生。可能我不明白@synchronized 在这方面的作用,究竟是什么被锁定。
【问题讨论】:
-
您可以查看the code here。见方法
captureOutput: didOutputSampleBuffer:fromConnection:
标签: ios objective-c asynchronous objective-c-blocks