2013-10-15 24 views
1

在下面的功能我想返回是從NSData的NSData得到釋放eventhough其used

  1. 創建當我給選項freeWhenDone = YESUIImage顯示的從這裏返回是白色圖像UIImage指針。
  2. 當我給選項freeWhenDone = NO

    • UIImage形式返回這裏展示它作爲一個黑色圖像。
    • 當我通過rgb_buffer(char數組)而不是[rgbData bytes]函數1和函數2正常工作。一切安好。

這是否與ARC有關?

Myfunction 
{ 
    char *pu1_out_buffer = malloc(length); 
    int width, height, stride; 
    char *rgb_buffer = malloc(BUFFER_LENGTH); 
pu1_out_buffer = datafromfile(FILE_PATH) // initialized with some data , not important 

/* rgb NSdata created from malloced rub buffer */ 
    NSMutableData *rgbData = [NSMutableData dataWithBytesNoCopy:rgb_buffer 
                length:(u4_stride * u4_height * 3) 
               freeWhenDone:YES]; 
[self function1:pu1_out_buffer 
      rgb_buffer:(UWORD16 *)[rgbData bytes] 
         …] 

    free(pu1_out_buffer); 
    UIImage *outUIImage = [self function2:rgbData   
             width:u4_width 
             height:u4_height 
             stride:u4_stride]; 

    return outUIImage; 
} 
+0

出於好奇:爲什麼你需要使用動態內存分配(malloc's)? –

+1

在不知道'function1','function2'的情況下回答爲什麼圖像是白色或黑色是不可能的。 –

+0

不相關但是'pu1_out_buffer = datafromfile(FILE_PATH)'=無效的語法和內存泄漏。 'MyFunction {'也是無效的,除非一個宏,請張貼一個真實的例子。 – Joe

回答

1

這段代碼有一些問題。

char *pu1_out_buffer = malloc(length); 
pu1_out_buffer = datafromfile(FILE_PATH) // initialized with some data , not important 

泄漏原來的malloc

[self function1:pu1_out_buffer 
     rgb_buffer:(UWORD16 *)[rgbData bytes] 
        …] 

這種方法應該是這樣的:function1:rgbBuffer: ...

至於崩潰,這是最有可能爲馬丁援引的理由。如果您啓用了ARC,則會從NSMutableData實例中抓取內部指針。 ARC無法將bytes的返回值與原始數據相關聯,假定數據對象不再被使用,並將其釋放。

要修復,添加:

[rgbData bytes]return outUIImage;之前。這將讓ARC知道該對象在撥打function2:width:height:stride:期間正在使用中。