【发布时间】:2011-10-15 06:15:33
【问题描述】:
我一直在拔头发,想弄清楚为什么会漏水。在我的 .h 文件中,我有一个综合属性 nonatomic,保留 NSMutableArray。在我的 viewDidLoad 中,我将其声明为:
self.tableData = [[NSMutableArray alloc] init];
[self.tableData removeAllObjects];
fillData(self.tableData);
在整个应用程序中,我调用 [self.tableData removeAllObjects],然后使用 fillData(self.tableData) 函数重新填充它。此函数从静态 C++ 字符串集中填充数据:
void fillData(NSMutableArray* list)
{
for (set<string>::const_iterator itr = sortedData.begin(); itr != sortedData.end(); ++itr){
[list addObject:[NSString stringWithFormat:@"%s", ((string)*itr).c_str()]];
}
}
在我的 dealloc 方法中我这样做:
[self.tableData removeAllObjects], [self.tableData release], tableData = nil;
我在哪里丢球了? Instruments 说它在 [list addObject....] 行中。
谢谢
【问题讨论】:
-
你的
((string)*itr).c_str()调用不是返回一个不是自动释放的字符串吗? -
是的,但是它被复制到一个应该自动释放的 NSString 中。所以我不确定这是如何导致泄漏的。我需要分配/自动释放该 NSString 吗?
-
看起来不错。如果将行一分为二,分成
const char*s=(*itr).c_str(); [list addObject:[NSString stringWithUTF8String:s];,会发生什么? -
顺便说一句,不鼓励在
stringWithFormat:中使用@"%s",因为不能指定使用的编码,这是非常危险的。例如,它可能会突然停止在俄罗斯 iPhone 上工作。使用stringWithUTF8String:或stringWithCString:encoding:error:。
标签: iphone objective-c memory-management nsmutablearray