NSData即使使用它也会被释放

时间:2013-10-15 13:30:19

标签: ios objective-c uiimage nsdata nsmutabledata

在下面的函数中,我试图返回从UIImage

创建的NSData指针
  1. 当我提供选项freeWhenDone = YES时,显示的UIImage显示为白色图像。
  2. 当我提供选项freeWhenDone = NO

      此处
    • UIImage返回表格将其显示为黑色图片。
    • 当我传递rgb_buffer(字符数组)而不是[rgbData bytes]时,function1和function2正常工作。一切都很好。
  3. 与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;
    }
    

1 个答案:

答案 0 :(得分: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:调用的持续时间内正在使用。

相关问题