2012-02-28 40 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

相關問題