【问题标题】:Memory leak on NSString stringByAppendingPathComponent:NSString stringByAppendingPathComponent 上的内存泄漏:
【发布时间】:2012-07-05 15:31:43
【问题描述】:

Analyze 显示内存泄漏,我在以下代码 sn-p 中为 fileB 分配了 filePath 值:

NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];

NSString *filePath = [docsDir stringByAppendingPathComponent:@"/fileA"];

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
    self.propertyA = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
} else {
    //  initialize array with default values and write to data file fileA   
    [self populatePropertyAForFile:filePath];       
}

filePath = [docsDir stringByAppendingPathComponent:@"/fileB"];

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
    self.propertyB = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
} else {
    // initialize array with default values and write to data file fileB

    [self populatePropertyBForFile:filePath];

}

我知道这是因为之前的值(对于 fileA)尚未发布。但我不知道如何阻止这种泄漏。

【问题讨论】:

  • 有些事情你没有告诉我们。

标签: objective-c ios


【解决方案1】:

没有。 filePath 没有任何问题。几乎可以肯定,问题出在您的两个属性propertyApropertyB 上。如果它们是保留属性,那么您分配给它们的数组及其内容将会泄漏,因为您拥有您分配的数组并且您没有释放它们。像这样更改行:

self.propertyA = [[[NSMutableArray alloc] initWithContentsOfFile:filePath] autorelease];
                                                                        // ^^^^^^^^^^^ will release ownership of the array

【讨论】:

  • hm.. 是的,我的错没有放自动释放。感谢您指出。也忘记了Xcode没有指向内存泄漏的位置,而是分配了对象泄漏内存的位置。
猜你喜欢
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 2014-06-06
  • 1970-01-01
  • 2011-10-05
相关资源
最近更新 更多