简体   繁体   English

setCompletionBlock在Objective-C中的奇怪行为

[英]strange behavior of setCompletionBlock in objective-c

GPUImageOutput<GPUImageInput> *filter;
GPUImageMovieWriter *movieWriter;
.
.
.
__block BOOL finished = NO;
__weak id weakMovieWriter = movieWriter;
[movieWriter setCompletionBlock:^{
    NSLog(@"Completed Successfully");
    __strong id strongMovieWritier = weakMovieWriter;
    [strongMovieWritier finishRecording];
    [filter removeTarget:strongMovieWritier];
    finished = YES;
    NSLog(finished ? @"Yes" : @"No");

}];
while (!finished);
[self completeTransaction]; // this method is not executed!!!

Concerning the above code the method [self completeTransaction] is not executed, even when i know the variable "finished" is changed to YES. 关于上述代码,即使我知道变量“ finished”已更改为“ YES”,也不会执行方法[self completeTransaction]。

But if i change this piece of code 但是如果我更改这段代码

while (!finished);

to

while (!finished){
    NSLog(@"Whatever");
}

The method [self completeTransaction] is called. 调用方法[self completeTransaction]。

Anybody know why this happens? 有人知道为什么会这样吗?

Thanks for your time. 谢谢你的时间。

reviewing again your code I think if 再次检查您的代码,我想如果

[self completeTransaction];

executes is rare because the completion block 执行很少,因为完成块

[movieWriter setCompletionBlock:^{
    NSLog(@"Completed Successfully");
    __strong id strongMovieWritier = weakMovieWriter;
    [strongMovieWritier finishRecording];
    [filter removeTarget:strongMovieWritier];
    finished = YES;
    NSLog(finished ? @"Yes" : @"No");

}];

executes a-synchronically and your [self completeTransaction]; 同步执行a和您的[self completeTransaction]; I assume that execute on main thread, I recommend you to do this 我假设在主线程上执行,我建议您这样做

GPUImageOutput<GPUImageInput> *filter;
GPUImageMovieWriter *movieWriter;
.
.
.
__weak id weakMovieWriter = movieWriter;
__weak weakSelf = self;
[movieWriter setCompletionBlock:^{
    NSLog(@"Completed Successfully");
    __strong id strongMovieWritier = weakMovieWriter;
    [strongMovieWritier finishRecording];
    [filter removeTarget:strongMovieWritier];
    [weakSelf completeTransaction];
}];

instead as I said on my previous comment, Hope this helps you 相反,正如我在之前的评论中所说,希望这对您有所帮助

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

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