检查图像(NSImage)分辨率泄漏内存

时间:2015-12-10 02:11:59

标签: objective-c cocoa memory-leaks nsimage

我有一个返回图像分辨率的函数(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(源代码)。但是没有变化。我怎样才能阻止泄漏?

Muchos thankos。

1 个答案:

答案 0 :(得分:1)

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

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

应该阻止你的记忆泄漏。