分析显示内存泄漏,我在以下代码片段中为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)尚未发布。但是我不知道如何阻止这种泄漏。
最佳答案
否。filePath没有任何问题。几乎可以肯定,问题在于您的两个属性propertyA
和propertyB
。如果它们是保留属性,那么您分配给它们的数组及其内容将泄漏,因为您拥有分配的数组并且没有释放它们。更改这样的行:
self.propertyA = [[[NSMutableArray alloc] initWithContentsOfFile:filePath] autorelease];
// ^^^^^^^^^^^ will release ownership of the array
关于objective-c - NSString stringByAppendingPathComponent上的内存泄漏:,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11347677/