如果我使用来自(__bridge)的CGImageSourceCreateWithData,是否需要“CFRelease”?

时间:2012-02-28 02:21:25

标签: iphone objective-c ios core-foundation

我的问题非常简单,我想知道方法“CGImageSourceCreateWithData”是否创建了一个复制我提供的数据的新对象,以便在不需要时我必须释放它它,或者它只是创建了对我已经拥有的数据的引用,这样如果我发布它,我将丢失这些数据(并且可能有错误的访问错误)。

该问题与使用(__bridge CFDataRef)作为源数据有关。让我在ARC模式下使用Core Foundation对象作为免费电话。

考虑以下函数(或方法,不确定它是如何调用的):

- (void)saveImageWithData:(NSData*)jpeg andDictionary:(NSDictionary*)dicRef andName:(NSString*)name
{
    [self setCapturedImageName:name];

    CGImageSourceRef  source ;

    // Notice here how I use __bridge
    source = CGImageSourceCreateWithData((__bridge CFDataRef)jpeg, NULL);

    CFStringRef UTI = CGImageSourceGetType(source); 

    NSMutableData *dest_data = [NSMutableData data];

    // And here I use it again
    CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)dest_data,UTI,1,NULL);

    CGImageDestinationAddImageFromSource(destination,source,0, (__bridge CFDictionaryRef) dicRef);

    BOOL success = NO;
    success = CGImageDestinationFinalize(destination);

    if(!success) {
        NSLog(@"***Could not create data from image destination ***");
    }

    // This only saves to the disk
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"ARPictures"];

    NSError *error;
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

    NSString *fullPath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", name]]; //add our image to the path

    [dest_data writeToFile:fullPath atomically:YES];


    self.img = [[UIImage alloc] initWithData:dest_data]; 
    self.capturedImageData = [[NSData alloc] initWithData:dest_data];

    //This is what im not sure if i should use
    CFRelease(destination);
    CFRelease(source);

}

我担心的是内存泄漏或处理我不应该做的事情。

谢谢

1 个答案:

答案 0 :(得分:7)

你正确地做到了。这些例程是否复制并不重要。重要的是你CFRelease你“创造”(或“复制”)。这里的一切看起来都很正确传递参数时__bridge是合适的,因为您实际上并没有将对象从CF转移到Cocoa,反之亦然。你只是暂时“衔接”(施放)它。