【发布时间】: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