我是 iPhone objectiveC 开发的新手。当我运行以下方法时出现内存泄漏。
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"dbname.sqlite"];
}
而且我发现如果我将它缩减到以下...它仍然会泄漏
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
return nil;
}
所以我尝试使用以下方法释放路径变量,但仍然会泄漏内存。
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
[paths release];
return nil;
}
为了检测泄漏,我在分析器中使用以下循环运行它:
for (int iLoop = 0; iLoop < 30; iLoop++) {
NSString *dbPath = [self getDBPath];
[dbPath release];
sleep(1);
}
与 NSPathStore2 和 NSArrayM 关联的内存量继续增长。
关于我可能做错了什么有什么建议吗? 谢谢!
最佳答案
您的 getDBPath 代码很好,但它可能是从没有任何自动释放池的上下文中调用的。
通过在循环代码中分配您自己的池来修复它:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (int iLoop = 0; iLoop < 30; iLoop++) {
NSString *dbPath = [self getDBPath];
// [dbPath release]; // do not release! dbPath will be autoreleased
sleep(1);
}
[pool drain];
关于iphone NSSearchPathForDirectoriesInDomains 内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5851848/