Fernando
Fernando

Reputation: 21

Garbage Collector and Core Foundation

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.

Upvotes: 0

Views: 526

Answers (2)

justin
justin

Reputation: 104698

the garbage collector does work with CoreFoundation types.

see CFMakeCollectable (excerpt from CF docs):

CFTypeRef CFMakeCollectable(CFTypeRef cf);

Makes a newly-allocated Core Foundation object eligible for garbage collection.

Parameters cf A CFType object to make collectable. This value must not be NULL. Return Value cf.

Discussion For more details, see Garbage Collection Programming Guide.

Upvotes: 2

w-m
w-m

Reputation: 11232

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.

Upvotes: 3

Related Questions