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