2012-02-28 38 views
3

我的问题很简单,我想知道如果方法“CGImageSourceCreateWithData”创建一个新的对象复制我提供的数据,以便我不再需要时发布它,或者如果它只是创建了一个对我已有的数据的引用,所以如果我释放它,我将失去这些数据(并可能有错误的访问错误)。如果我使用(__bridge)的CGImageSourceCreateWithData,是否需要“CFRelease”?

该问题与使用(__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); 

} 

我担心的是内存泄漏,或者我不应该dealocating事情。

谢谢

回答

7

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

+0

哦,我明白了,所以基本上我创造了我应该始终释放权利?我有点困惑,因为我想优化这个代码,并且正在考虑使用可可对象直接桥接它们的可能性,以便我没有这些额外的2个副本。现在我有了原始数据(来自jpeg数据),源和目的地,甚至我释放了最后2个过程似乎消耗了大量的内存。这可以做到吗? btw感谢您的快速回复 – Pochi 2012-02-28 02:44:37

+1

您需要用名称中包含Create或Copy的任何方法来平衡CFRelease。至于其他方面,我不确定你为什么在这里使用Core Graphics。你可以用'imageWithData:'将JPEG数据转换成UIImage。你在那里做更复杂的事情吗? – 2012-02-28 03:32:44

+0

是的,我通过添加一些额外信息来修改图像中的元数据,所以我认为这是修改数据的唯一方法。 – Pochi 2012-02-28 03:41:00

相关问题