在ARC中生成CGImagesAsynchronouslyForTimes

如果我在启用ARC的项目中运行以下项目,则完成处理程序不会触发。 但没有ARC,它按预期工作。 我在这里错过了什么?

NSURL *url = [NSURL URLWithString:@"http://media.w3.org/2010/05/sintel/trailer.mp4"]; AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:url options:nil]; AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset]; generator.appliesPreferredTrackTransform = YES; CMTime thumbTime = CMTimeMakeWithSeconds(5,30); AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){ NSLog(@"completion handler"); }; generator.maximumSize = CGSizeMake(320, 180); [generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler]; 

基于迈克尔指出,发电机没有得到保留,如果你只是“使用”发电机瓦内完成块,一切都会工作。

所以我想答案是…

 NSURL *url = [NSURL URLWithString:@"http://media.w3.org/2010/05/sintel/trailer.mp4"]; AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:url options:nil]; AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset]; generator.appliesPreferredTrackTransform = YES; CMTime thumbTime = CMTimeMakeWithSeconds(5,30); AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){ NSLog(@"make sure generator is used in this block and it'll work %@", generator); }; generator.maximumSize = CGSizeMake(320, 180); [generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler]; 

看起来像generateCGImagesAsynchronouslyForTimes不保留生成器。 使发生器成为您的实例的成员variables并分配给它。 只要我这样做,它开始工作。 代码将如下所示:

 NSURL *url = [NSURL URLWithString:@"http://media.w3.org/2010/05/sintel/trailer.mp4"]; AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:url options:nil]; [generator_ cancelAllCGImageGeneration]; generator_ = [[AVAssetImageGenerator alloc] initWithAsset:asset]; generator_.appliesPreferredTrackTransform = YES; CMTime thumbTime = CMTimeMakeWithSeconds(5,30); AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){ NSLog(@"completion handler"); }; generator_.maximumSize = CGSizeMake(320, 180); [generator_ generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler]; 

图像生成器肯定不会被框架保留。 不知道多久苹果编程指南得到更新,但你可以阅读AV Foundation Prog。 指南,很清楚地生成一系列图像 :

此外,您必须确保您保留图像生成器,直到完成图像创build。