I have a strange problem while saving number of big images (from camera) to the filesystem one after another in loop.
If I place [NSThread sleepForTimeInterval:1.0]; in each loop, than memory is released just fine after every image processing. But without that sleep interval, memory allocation increases above the roof and eventually app crashes…
Could someone please explain how to avoid this or to deallocate memory after each loop?
Btw, I’m developing on iOS 5…
This is the my code:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (NSDictionary *imageInfo in self.imageDataArray) {
[assetslibrary assetForURL:[NSURL URLWithString:imageUrl] resultBlock:^(ALAsset *asset) {
CGImageRef imageRef = [[asset defaultRepresentation] fullResolutionImage];
if (imageRef) {
[sharedAppSettingsController saveCGImageRef:imageRef toFilePath:filePath];
imageRef = nil;
[NSThread sleepForTimeInterval:1.0];
//CFRelease(imageRef);
}
} failureBlock:^(NSError *error) {
NSLog(@"booya, cant get image - %@",[error localizedDescription]);
}];
}
// tell the main thread
dispatch_async(dispatch_get_main_queue(), ^{
//do smth on finish
});
});
And this is the method for saving CGImage to FS:
- (void)saveCGImageRef:(CGImageRef)imageRef toFilePath:(NSString *)filePath {
@autoreleasepool {
CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:filePath];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypeJPEG, 1, NULL);
CGImageDestinationAddImage(destination, imageRef, nil);
bool success = CGImageDestinationFinalize(destination);
if (!success) {
NSLog(@"Failed to write image to %@", filePath);
}
else {
NSLog(@"Written to file: %@",filePath);
}
CFRelease(destination);
}
}
The problem is that you call “assetForURL” in a for loop. This method will begin loading all of your images simultaneously each on a separate thread. You should begin loading 1 image and in completion block continue with loading the next one. I suggest you use some kind of recursion.