开发者

How to release CGImageRef correctly?

开发者 https://www.devze.com 2023-04-08 22:59 出处:网络
My Code like this: CGImageRef ImageCreateWithFile(NSString *filePath) { if(NULL == filePath) return NULL;

My Code like this:

CGImageRef ImageCreateWithFile(NSString *filePath)
{ 
  if(NULL == filePath)
    return NULL;

  NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
  if(NULL == data)
    return NULL;

  CGImageSourceRef isrc = CGImageSourceCreateW开发者_JAVA百科ithData((CFDataRef)data, NULL);
  // [data release];

  CGImageRef image = CGImageSourceCreateImageAtIndex(isrc, 0, NULL);

  CFRelease(isrc);
  isrc = nil;
  [data release];
  data = nil;

  return  image;
}

- (IBAction)addClick:(id)sender
{
  CGImageRef image = ImageCreateWithFile(@"/Users/user/t.jpg");

  if(NULL != image)
    _imageList.push_back(image);
}

- (IBAction)removeClick:(id)sender
{
  if(_imageList.size() > 0)
  {
    CGImageRef image = _imageList[0];
    CGImageRelease(image);
    image = nil;

    _imageList.erase(_imageList.begin());
  }
}

The imageList declared like:

 std::vector<CGImageRef> _imageList;

This program is wrote for testing the method of releasing CGImageRef. When I add some images, I see the memory usage of the program rises regularly in the Activity Monitor,but after I remove one or more images by the remove method, the memory never descend. I don't know why the release method not work? Any help? Thanks!!!


If you look at the documentation of CGImageSourceCreateImageAtIndex, you'll see that the last argument is a dictionary of options.

One of these options is called kCGImageSourceShouldCache.

You could try to pass a dictionary, setting this option to false. The snippet below is from the Image I/O Guide here

CFStringRef       myKeys[1];
CFTypeRef         myValues[1];
CFDictionaryRef   myOptions;

myKeys[0] = kCGImageSourceShouldCache;
myValues[0] = (CFTypeRef)kCFBooleanFalse;

myOptions = CFDictionaryCreate(NULL, (const void **) myKeys,
               (const void **) myValues, 1,
               &kCFTypeDictionaryKeyCallBacks,
               & kCFTypeDictionaryValueCallBacks);

CGImageRef image = CGImageSourceCreateImageAtIndex(isrc, 0, myOptions);
0

精彩评论

暂无评论...
验证码 换一张
取 消