我有一些代码将所有目录从“/ Documents”复制到“Library / Caches /”。代码如下:
NSString *oldPath = [NSString stringWithFormat:@"%@/Documents/", NSHomeDirectory()];
NSString *newPath = [NSMutableString stringWithFormat:@"%@/Library/Caches/", NSHomeDirectory()];
NSError *error = nil;
// get the list of all files and directories
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *fileList = [fileManager contentsOfDirectoryAtPath:oldPath error:&error];
if(error != nil)
{
NSLog(@"\n\n\n1. There was an error in the file operation: %@", [error localizedDescription]);
return;
}
for(NSString *file in fileList)
{
NSString *path = [oldPath stringByAppendingPathComponent:file];
NSLog(@"The path for the file is: %@", path);
BOOL isDir = NO;
BOOL dirExists = [fileManager fileExistsAtPath:path isDirectory:(&isDir)];
if(isDir && dirExists)
{
//Move to the new location
[fileManager copyItemAtPath:path toPath:[newPath stringByAppendingPathComponent:file] error:&error];
if(error != nil)
{
NSLog(@"\n\n\n2. There was an error in the file operation: %@", [error localizedDescription]);
}
else
{
[fileManager removeItemAtPath:path error:&error];
if(error != nil)
NSLog(@"\n\n\n3. There was an error in the file operation: %@", [error localizedDescription]);
}
}
}
副本工作正常。我可以看到所有目录都被复制到新位置。
问题是空目录仍保留在Documents文件夹中。我在文档中阅读removeItemAtPath
,并说它删除了目录的内容。是否删除了实际目录本身。
有人能告诉我代码中可能出现的问题吗?为什么空目录仍然存在?
编辑:
在第一次传递时,当目录存在于Documents中但不存在于Library / Caches中时,removeItemAtPath
不会抛出错误。但是,空目录仍保留在Documents中。在上面的代码的第二遍,它试图删除空目录,removeItemAtPath
抛出一个可可错误516,基本上没找到文件 - 这很奇怪,因为我仍然可以看到那些空目录。
另外,我在iPhone模拟器4.3.2和iPhone模拟器5.0上运行此代码,并在/ Users / Library / Application Support / iPhone模拟器中监控我的Mac上的目录结构/....
答案 0 :(得分:3)
由于“/ Documents /”中的尾部“/”,可能会发生这种情况。尝试从前两行删除尾部“/”,或使用:
NSString *oldPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *newPath = [NSString pathWithComponents:[NSArray arrayWithObjects:NSHomeDirectory() , @"Library", @"Caches", nil]];
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *fileList = [fileManager contentsOfDirectoryAtPath:oldPath error:&error];
if (error) {
NSLog(@"\n\n\n1. There was an error in the file operation: %@", [error localizedDescription]);
return;
}
for (NSString *file in fileList) {
NSString *path = [oldPath stringByAppendingPathComponent:file];
NSLog(@"The path for the file is: %@", path);
BOOL isDir = NO;
if ([fileManager fileExistsAtPath:path isDirectory:&isDir] && isDir) {
[fileManager copyItemAtPath:path toPath:[newPath stringByAppendingPathComponent:file] error:&error];
if(error) {
NSLog(@"\n\n\n2. There was an error in the file operation: %@", [error localizedDescription]);
} else {
[fileManager removeItemAtPath:path error:&error];
if (error) {
NSLog(@"\n\n\n3. There was an error in the file operation: %@", [error localizedDescription]);
}
}
}
}