使用NSFileManager不会移动文件

时间:2016-01-18 04:05:03

标签: ios objective-c nsfilemanager

我正在尝试使用NSFileManager将文件从Documents / Inbox文件夹移动到Documents文件夹。我使用断点来确定我的代码不工作的地方,并且一切似乎都运行良好,直到它碰到实际移动文件的部分。找到目录并在调试器中记录文件,但它不会移动。这是我的整个viewDidLoad方法([super viewDidLoad];中没有任何内容):

//Turn every file inside the directory into an array
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *appFolderPath = [path objectAtIndex:0];
NSString *inboxAppFolderPath = [appFolderPath stringByAppendingString:@"/Inbox"]; //changes the directory address to make it for the inbox

//NSPredicates to filter out files I don't want in my NSArray
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"not SELF beginswith[c] '.DS_Store'"];
NSPredicate *inboxPredicate = [NSPredicate predicateWithFormat:@"not SELF beginswith[c] 'Inbox'"];
recipes = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:appFolderPath error:nil];
recipes = [recipes filteredArrayUsingPredicate:predicate];
recipes = [recipes filteredArrayUsingPredicate:inboxPredicate];




//get to inbox directory
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSArray *inboxContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:inboxAppFolderPath,documentsDirectory] error:nil];

//move all the files over
for (int i = 0; i != [inboxContents count]; i++)
{
    NSString *oldPath = [NSString stringWithFormat:inboxAppFolderPath, documentsDirectory, [inboxContents objectAtIndex:i]];
    NSString *newPath = [NSString stringWithFormat:appFolderPath, documentsDirectory, [inboxContents objectAtIndex:i]];
    [[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:nil];
}

1 个答案:

答案 0 :(得分:0)

在Documents中创建子文件夹可能会有问题。

尝试以这种方式创建 inboxAppFolder

NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString *inboxAppFolderPath = [path stringByAppendingPathComponent:@"Inbox"];  // subDirectory

if (![[NSFileManager defaultManager] fileExistsAtPath: inboxAppFolderPath])
   [[NSFileManager defaultManager] createDirectoryAtPath: inboxAppFolderPath withIntermediateDirectories:NO attributes:nil error:nil];

//Rest of your code

希望,它会帮助你。
感谢。