【发布时间】:2010-06-16 07:37:27
【问题描述】:
Mac OS X 10.6,Cocoa 项目,带有保留/释放 gc
我有一个函数:
- 遍历特定目录,扫描子文件夹(包括嵌套文件夹),构建字符串 NSMutableArray(每个找到的子文件夹路径一个字符串),然后返回该数组。
例如(为简洁起见,删除了错误处理)。
NSMutableArray * ListAllSubFoldersForFolderPath(NSString *folderPath)
{
NSMutableArray *a = [NSMutableArray arrayWithCapacity:100];
NSString *itemName = nil;
NSFileManager *fm = [NSFileManager defaultManager];
NSDirectoryEnumerator *e = [fm enumeratorAtPath:folderPath];
while (itemName = [e nextObject]) {
NSString *fullPath = [folderPath stringByAppendingPathComponent:itemName];
BOOL isDirectory;
if ([fm fileExistsAtPath:fullPath isDirectory:&isDirectory]) {
if (isDirectory is_eq YES) {
[a addObject: fullPath];
}
}
}
return a;
}
调用函数在每个会话中只获取一次数组,保留它以供以后处理:
static NSMutableArray *gFolderPaths = nil;
...
gFolderPaths = ListAllSubFoldersForFolderPath(myPath);
[gFolderPaths retain];
在这个阶段一切看起来都很好。 [gFolderPaths count] 返回找到的正确路径数,[gFolderPaths description] 打印出所有正确的路径名。
问题:
当我稍后使用 gFolderPaths 时(例如,下一次运行我的事件循环)我的断言代码(以及 Xcode 中的 gdb)告诉我它是 nil。
在那次初始抓取之后,我没有以任何方式修改 gFolderPaths,所以我假设我的内存管理被搞砸了,并且 gFolderPaths 正在被运行时释放。
我的假设/假设
当我将每个字符串添加到可变数组时,我不必保留它,因为这是自动完成的,但是一旦数组从函数交给我,我就必须保留它,因为我不会立即使用它。这是正确的吗?
感谢任何帮助。
【问题讨论】: