防止循环循环,直到内循环写入磁盘

时间:2015-04-27 15:30:09

标签: ios objective-c grand-central-dispatch nsdata

我有一个嵌套的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)];
}

1 个答案:

答案 0 :(得分:3)

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

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];
        }
    }
}