我有一个6的NSArray,CMTimes看起来像这样:
(
"CMTime: {0/600 = 0.000}",
"CMTime: {600/600 = 1.000}",
"CMTime: {1200/600 = 2.000}",
"CMTime: {1800/600 = 3.000}",
"CMTime: {2400/600 = 4.000}",
"CMTime: {3000/600 = 5.000}",
"CMTime: {3600/600 = 6.000}"
)
然后用我的方法
NSValue *myTime = [times objectAtIndex:i];
NSArray *array = [[NSArray alloc] initWithObjects:myTime, nil];
//Also all these get logged before anything inside block is logged, when I
//looping the whole thing
NSLog(@"%@", array);
[imageGenerator generateCGImagesAsynchronouslyForTimes:array completionHandler:^(CMTime requestedTime, CGImageRef image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) {
//HERE its not in order
NSString *requestedTimeString = (NSString *) CFBridgingRelease(CMTimeCopyDescription(NULL, requestedTime));
NSString *actualTimeString = (NSString *) CFBridgingRelease(CMTimeCopyDescription(NULL, actualTime));
NSLog(@"Requested: %@; actual %@", requestedTimeString, actualTimeString);
我是一个NSInteger并且通过循环增加。然后在下一行中,我将一个值的数组传递给imageGenerator generateCGImagesAsynchronouslyForTimes
但是,当我在generateCGImagesAsynchronouslyForTimes
方法中执行此操作时,时间乱序,即使在我记录它们之前有一行它们是有序的吗?
这里发生了什么,我该如何解决?
感谢您的帮助。
修改
答案 0 :(得分:1)
看起来您正在创建单独的一个条目数组,然后将它们传递给异步方法。我相信generateCGImagesAsynchronouslyForTimes:handler方法的目的是批处理操作(你可能正在为它做这个工作吗?)。现在事情可以以任何顺序返回(或者可能在单独的线程上使问题复杂化)。
尝试立即传递整个数组(次)。
或者,完成处理程序提供了足够的信息,您可以按排序顺序将图像插入到不同的集合中。
回应你的意见:
NSMutableArray *completedList = [NSMutableArray array];
__block count = [array count];
[imageGenerator generateCGImagesAsynchronouslyForTimes:array completionHandler:^(CMTime requestedTime, CGImageRef image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) {
// Check the time here, insert the items to the array in order using something like
[completedList insertObject: image atIndex: indexThatItShouldGoInOrder];
// Or adding them all and sorting them at the end, whichever is easier
count--; // Wait till you have them all
if(!count) {
// Here trigger the other stuff you were going to do because it's done.
}
}];
如果处理程序在多个线程上运行,则可能需要更复杂一些。您将需要使用GCD来保护阵列/排序/插入。您还需要确保count--,检查计数是原子的。
根据您尝试做的事情,在if(!count)块中执行dispatch_async()也可能有意义。