2013-08-06 148 views
3

我有用於轉換的NSMutableString對象爲NSData對象制定了未來代碼:如何在iOS中正確釋放內存:內存永遠不會釋放;內存潛在泄漏指向

-(NSData *)desSerializarFirma:(NSMutableString *)firma{ 

    NSArray *arregloBits = [firma componentsSeparatedByString:@","]; 
    unsigned c    = arregloBits.count; 
    uint8_t *bytes   = malloc(sizeof(*bytes) * c); 

    unsigned i; 
    for (i = 0; i < c; i ++) 
    { 
     NSString *str = [arregloBits objectAtIndex:i]; 
     int byte = [str intValue]; 
     bytes[i] = (uint8_t)byte; 
    } 

    return [NSData dataWithBytes:bytes length:c]; 
} 

當我分析這和Xcode它說

memory is never released; potential leak of memory pointed to by 'bytes' 

這個語句指向我的代碼的最後一行:

return [NSData dataWithBytes:bytes length:c]; 

如果我通過執行釋放對象「自由(字節)」然後我得到我的FUNC灰沒用...任何幫助,我會欣賞

+1

你只需要釋放它,當你用它做替代

return [NSData dataWithBytes:bytes length:c]; 

。 –

+0

你是對的,你的答案和dasblinkenlight的幫助我可以解決它,謝謝 –

回答

6

你需要free的字節,因爲NSData不承擔它的所有權:它不知道如果該數組是一個臨時或動態,所以它使副本它。

要解決此問題,

NSData *res = [NSData dataWithBytes:bytes length:c]; 
free(bytes); 
return res; 
+1

嘿它的工作!感謝你的回答,我以這種方式開發了這個功能,因爲我只想把代碼縮減到儘可能小的表達式,並且它表明更少的代碼並不總是最好的,謝謝! –