本文介绍了如何在iOS中正确释放内存:永远不会释放内存;指出的潜在的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开发了下一个代码,用于将NSMutableString对象转换为NSData对象:
I have the next code developed for converting an NSMutableString object into NSData object:
-(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分析时说
when I analyze this with xCode it says
memory is never released; potential leak of memory pointed to by 'bytes'
此语句指向我的代码的最后一行:
this statement points to the last line of my code:
return [NSData dataWithBytes:bytes length:c];
如果我通过执行'free(bytes)'释放对象,那么我的函数将变得无用……任何帮助,我将不胜感激
if I release the object by executing 'free(bytes)' then I get my function useless... any help I'll appreciate
推荐答案
您需要free
个字节,因为NSData
不拥有它的所有权:它不知道该数组是临时数组还是动态数组,因此它会复制它.
You need to free
the bytes, because NSData
does not take ownership of it: it cannot know if the array is a temporary or a dynamic, so it makes a copy of it.
要解决此问题,请替换
return [NSData dataWithBytes:bytes length:c];
使用
NSData *res = [NSData dataWithBytes:bytes length:c];
free(bytes);
return res;
这篇关于如何在iOS中正确释放内存:永远不会释放内存;指出的潜在的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!