views:

48

answers:

2

Hi,

I wrote a method for load Image into CALayer. This is the code:

- (CGImageRef)loadImage:(NSString*)path {
          // Get data image
          CGImageRef image = NULL;
          NSData *data = [NSData dataWithContentsOfFile:path];
          CFDataRef imgData = (CFDataRef)data;
          CGDataProviderRef imgDataProvider = CGDataProviderCreateWithCFData (imgData);

          // Get CGImage from CFDataRef
          image = CGImageCreateWithJPEGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault);

          // If the image isn't a JPG Image, would be PNG file
          if (!image)
               image = CGImageCreateWithPNGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault);

          return image;
}

I use this method in my CALayer:

NSString *pathString = // my image path;
aLayer = [CALayer layer];
aLayer.contents = [self loadImage:pathString];

It's work. I finalize my view (using garbage collector) but my application has leaks. Should I release CFDataRef imgData? I read that garbage collector does not work in Core Foundation.
Thanks and excuse my english.

+1  A: 

You are responsible for releasing this object by calling CGImageRelease.

See the documentation on garbage collection:

http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/GarbageCollection/Articles/gcCoreFoundation.html

By default, therefore, in a garbage-collected environment you manage Core Foundation objects exactly as you would in a reference-counted environment (as described in Memory Management Programming Guide for Core Foundation > “Ownership Policy”). If you create or copy a Core Foundation object, you must subsequently release it when you’re finished with it. If you want to keep hold of a Core Foundation object, you must retain it and again subsequently release it when you’re finished with it.

w.m
First, thank you for your answer. How I should write finalize method? would this code be correct?: CGImageRelease(aLayer.content);aLayer = nil
Fernando
The contents is retained by the layer, so you can release it immediately after the aLayer.contents assignment. Keep in mind that you should not use a name like loadImage, but instead createImage, as you own the image that is returned (see Memory Management Programming Guide for Core Foundation).
w.m
Thank you!! I try it.
Fernando