gpt4 book ai didi

ios - 是在主线程中调用 AVAssetImageGenerator 完成处理程序吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:16:50 24 4
gpt4 key购买 nike

  1. 我正在尝试从视频中获取一组图像。它运行良好,但我怀疑完成处理程序是在哪个线程中调用的。

  2. 我在新操作中调用了此方法 (generateCGImagesAsynchronouslyForTimes:),并在完成处理程序中更新了 UI。用户界面得到更新。

  3. 但通常 UI 更新不会发生在辅助线程中?我怀疑是在当前调用线程还是主线程中调用了完成处理程序?

我的代码是:

__block unsigned int i = 0;
AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){

i++;
if(result == AVAssetImageGeneratorSucceeded){

//Create a block to save the image in disk
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory()
stringByAppendingPathComponent:@"Documents"];
NSError *error = nil;

//Create file path for storing the image
NSString *videoOutputPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"VideoFrames%i.png", i]];

//Delete if already any image exist
if ([fileMgr fileExistsAtPath:videoOutputPath]){
if ([fileMgr removeItemAtPath:videoOutputPath error:&error] != YES)
NSLog(@"Unable to delete file: %@", [error localizedDescription]);
}

//Convert the CGImageRef to UIImage
UIImage *image = [UIImage imageWithCGImage:im];//**This line gives error: EXE_BAD_ACCESS**

//Save the image
if(![UIImagePNGRepresentation(image) writeToFile:videoOutputPath options:NSDataWritingFileProtectionNone error:&error])
NSLog(@"Failed to save image at path %@", videoOutputPath);
}];

//Add the operation to the queue
[self.imageWritingQueue addOperation:operation];
}
}
};

最佳答案

文档清楚地说明了这一点:

Concurrent Programming with AV Foundation

Callouts from AV Foundation—invocations of blocks, key-value observers, and notification handlers—are not guaranteed to be made on any particular thread or queue. Instead, AV Foundation invokes these handlers on threads or queues on which it performs its internal tasks. You are responsible for testing whether the thread or queue on which a handler is invoked is appropriate for the tasks you want to perform. If it’s not (for example, if you want to update the user interface and the callout is not on the main thread), you must redirect the execution of your tasks to a safe thread or queue that you recognize, or that you create for the purpose.

另请参阅:AV Foundation Programming Guide

编辑:

问题是,您没有保留/释放参数 im 中提供的 CGImageRef 图像,因为您稍后会在 NSBlockOperation 中使用它。在调用 block 之前,您需要在 block 外(从 NSBlockOperation)保留它,并在 block 返回之前(在 block 内)释放它。

关于ios - 是在主线程中调用 AVAssetImageGenerator 完成处理程序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21496043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com