在iPhone应用程序中的内存泄漏问题

时间:2011-04-23 05:34:14

标签: iphone nsstring

我收到以下代码的泄密。

            cell.lblNoOfReplay.text=[NSString stringWithFormat:@"0 Replies. %@",(NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)[[NSString stringWithFormat:@"Last message on %@",[BabbleVilleAppDelegate dateByAddingHours:Babbleoffset withDate:[[arrayPMMainList objectAtIndex:[indexPath section]] objectForKey:@"datetime"]]] stringByReplacingOccurrencesOfString:@"+" withString:@" "], CFSTR(""), kCFStringEncodingUTF8)];

这里我没有分配任何字符串但是当我检查内存泄漏时,上面的行中有一些泄漏。 可能它可能是由于kCFAllocatorDefault,所以某些人遇到了同样的问题,帮助我。

此致 Mrugen

1 个答案:

答案 0 :(得分:5)

是的,你已经分配了一个字符串。 Core Foundation对象遵循Create rule:通过名称包含Create或Copy的函数获取的任何对象都由调用者拥有,并且必须在调用者完成使用后释放。

将您的代码更改为:

CFStringRef s = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)[[NSString stringWithFormat:@"Last message on %@",[BabbleVilleAppDelegate dateByAddingHours:Babbleoffset withDate:[[arrayPMMainList objectAtIndex:[indexPath section]] objectForKey:@"datetime"]]] stringByReplacingOccurrencesOfString:@"+" withString:@" "], CFSTR(""), kCFStringEncodingUTF8);
cell.lblNoOfReplay.text=[NSString stringWithFormat:@"0 Replies. %@", (NSString *)s];
CFRelease(s);

另外,考虑将该行分成多个部分和中间变量。其他看到该代码的人,包括你未来的自己,会感谢你。