0

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.

4

2 回答 2

3

你负责通过调用 CGImageRelease 来释放这个对象。

请参阅有关垃圾收集的文档:

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

因此,默认情况下,在垃圾收集环境中,您管理 Core Foundation 对象的方式与在引用计数环境中完全相同(如 Core Foundation 的内存管理编程指南 > “所有权策略”中所述)。如果您创建或复制 Core Foundation 对象,则必须在完成后释放它。如果你想保留一个核心基础对象,你必须保留它,然后在你完成它时再次释放它。

于 2010-10-07T15:02:35.347 回答
2

垃圾收集器确实适用于 CoreFoundation 类型。

参见 CFMakeCollectable(摘自 CF 文档):

CFTypeRef CFMakeCollectable(CFTypeRef cf);

使新分配的 Core Foundation 对象符合垃圾回收的条件。

参数cf一个可收集的 CFType 对象。此值不得为 NULL。返回值cf

讨论 有关更多详细信息,请参阅垃圾收集编程指南。

于 2010-11-07T18:57:08.740 回答