【问题标题】:Checking Image (NSImage) Resolutions Leaks Memory检查图像(NSImage)分辨率泄漏内存
【发布时间】:2016-03-15 12:54:19
【问题描述】:

我有一个返回图像分辨率的函数 (NSImage)。该应用程序允许用户选择一个文件夹,它会使用 NSMutableArray 支持的列表 (NSTableView) 列出其中每个文件的分辨率。

- (NSSize)getImageResolutions:(NSString *)path {
    NSURL *url = [[NSURL alloc] init];
    url = [NSURL fileURLWithPath:path isDirectory:NO];
    CGImageSourceRef source = NULL;
    if (url) {
        source = CGImageSourceCreateWithURL((__bridge CFURLRef)url,NULL);
        if (source) {
            NSDictionary *props = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source,0,NULL);
            NSString *width = [props objectForKey:@"DPIWidth"];
            NSString *height = [props objectForKey:@"DPIHeight"];
            NSSize size;
            if ([width floatValue] > 0 && [height floatValue] > 0) {
                size = NSMakeSize([width floatValue],[height floatValue]);
                return size;
            }
            else {
                NSImage *img0 = [[NSImage alloc] initWithContentsOfFile:path];
                NSArray *imageReps = [[NSArray alloc] init];
                imageReps = [NSBitmapImageRep imageRepsWithContentsOfFile:path];
                NSInteger width = 0;
                NSInteger height = 0;
                for (NSImageRep *imageRep in imageReps) {
                    if ([imageRep pixelsWide] > width) width = [imageRep pixelsWide];
                    if ([imageRep pixelsHigh] > height) height = [imageRep pixelsHigh];
                }
                NSImage *imageNSImage = [[NSImage alloc] initWithSize:NSMakeSize((CGFloat)width,(CGFloat)height)];
                [imageNSImage addRepresentations:imageReps];
                NSImage *img1 = imageNSImage;
                return NSMakeSize(img1.size.width/img0.size.width*72.0f,img1.size.height/img0.size.height*72.0f);
            }
        } else {
            return NSMakeSize(0,0);
        }
    } else {
        return NSMakeSize(0,0);
    }

    CFRelease(source);
}

如果我选择一个包含大约 200 张图像的文件夹,内存使用量将增加大约 100 MB。肯定有漏我已经追踪到上面函数的来源。我 100% 确定这是来源,因为如果我不使用上面的功能,应用程序内存将增加不超过 10 MB,文件夹包含 200 多个图像。我做了一些调整,比如添加 CFRelease(source)。但没有任何变化。我怎样才能阻止泄漏?

非常感谢。

【问题讨论】:

    标签: objective-c cocoa memory-leaks nsimage


    【解决方案1】:

    请注意,CFRelease(source); 永远不会被执行。

    NSDictionary *props = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source,0,NULL);
    NSString *width = [props objectForKey:@"DPIWidth"];
    NSString *height = [props objectForKey:@"DPIHeight"];
    CFRelease(source);
    

    应该阻止你的内存泄漏。

    【讨论】:

    • 这是阻止我的内存泄漏的解决方案?
    • 是的,在调用CGImageSourceCreateWithURL 后正确使用CFRelease(source); 可能会阻止内存泄漏。
    • @ElTomato - 他们有一个观点。您的CFRelease(source) 无法访问。
    • 那我该如何改进呢?
    猜你喜欢
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    相关资源
    最近更新 更多