Не удается сохранить CIImage в файл на iOS без утечек памяти

Следующий фрагмент кода сохранить CIImage на диск с помощью UIImage,

- (void)applicationWillResignActive:(UIApplication *)application
{
    NSString* filename = @"Test.png";

    UIImage *image = [UIImage imageNamed:filename];

    // make some image processing then store the output
    CIImage *processedImage = [CIImage imageWithCGImage:image.CGImage];

#if 1// save using context

    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef cgiimage = [context createCGImage:processedImage fromRect:processedImage.extent];
    image = [UIImage imageWithCGImage:cgiimage];

    CGImageRelease(cgiimage);

#else

    image = [UIImage imageWithCIImage:processedImage];

#endif

    // save the image

    NSString *filePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:[@"../Documents/" stringByAppendingString:filename]];

    [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
}

Тем не менее, это утечка CGImageRef даже когда он выпущен по телефону CGImageRelease

Если строка с #if 1 изменено на #if 0, UIImage создается непосредственно из CIImage и нет утечек памяти, но тогда UIImage не сохраняется на диск

1 ответ

Оберните экономию в пул авто-релизов:

- (void)applicationWillResignActive:(UIApplication *)application
{
    NSString* filename = @"Test.png";

    UIImage *image = [UIImage imageNamed:filename];

    // make some image processing then store the output
    CIImage *processedImage = [CIImage imageWithCGImage:image.CGImage];

    @autoreleasepool {
        CIContext *context = [CIContext contextWithOptions:nil];
        CGImageRef cgiimage = [context createCGImage:processedImage fromRect:processedImage.extent];
        image = [UIImage imageWithCGImage:cgiimage];

        CGImageRelease(cgiimage);

        // save the image
        NSURL *documentsDir = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
        NSURL *fileURL = [documentsDir URLByAppendingPathComponent:filename];

        [UIImagePNGRepresentation(image) writeToURL:fileURL atomically:YES];
    }
}

Также обратите внимание, что я обновил информацию о том, как вы извлекали каталог Documents для работы на iOS 8 ( подробнее).

Другие вопросы по тегам