在内部循环写入磁盘之前防止循环循环

Prevent loop from looping until inner loop writes to disk

我有一个嵌套的 for 循环,我多次调用 getSnapShotData 方法并将此数据写入磁盘。我注意到这样做会增加太多内存,我 运行 内存不足,所以我认为这将是使用 dispatch semaphore.

的一个很好的用例

我仍然运行内存不足,所以我不确定我是否正确使用了信号量。本质上,我希望下一个循环等到前一个循环的数据写入磁盘,因为我认为这将释放内存。但我可能是错的。谢谢你的帮助。

代码:

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

for (NSDictionary *sub in self.array)
{
    NSArray *lastArray = [sub objectForKey:@"LastArray"];

    for (NSDictionary *dict in lastArray)
    {
        currentIndex ++;

        NSData *frame = [NSData dataWithData:[self getSnapshotData]];

        savePath = [NSString stringWithFormat:@"%@/%lu.png",frameSourcePath,(unsigned long)currentIndex];

        BOOL nextLoop = [frame writeToFile:savePath options:0 error:nil];

        frame = nil;

        if (nextLoop)
        {
            dispatch_semaphore_signal(sema);
        }

        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }
}

- (NSData *)getSnapshotData
{
    UIGraphicsBeginImageContextWithOptions(self.containerView.bounds.size, NO, 0.0);
    [self.containerView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snapShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return [NSData dataWithData:UIImagePNGRepresentation(snapShot)];
}

您有太多自动释放的对象。添加一个自动释放池来改善这种情况,而不是使用信号量。

for (NSDictionary *sub in self.array)
{
    NSArray *lastArray = [sub objectForKey:@"LastArray"];

    for (NSDictionary *dict in lastArray)
    {
        @autoreleasepool {
            currentIndex ++;

            NSData *frame = [NSData dataWithData:[self getSnapshotData]];

            savePath = [NSString stringWithFormat:@"%@/%lu.png",frameSourcePath,(unsigned long)currentIndex];

            BOOL nextLoop = [frame writeToFile:savePath options:0 error:nil];
        }
    }
}