因为我可以将所有文件从一个目录移动到Objective-C中的另一个目录?

时间:2014-12-16 17:18:51

标签: ios file nsfilemanager

因为我可以将所有文件从一个目录移动到另一个目录吗?我有我的代码,所以单独移动它们,但我无法移动它们。

 NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"user"];

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



    NSString *oldPath = [NSString stringWithFormat:@"%@/user/%@", documentsDirectory, fileName];

     NSLog(@"copia de aqui %@", oldPath);
    NSString *newPath = [NSString stringWithFormat:@"%@/leidos/%@", documentsDirectory, fileName];
     NSLog(@"aqui aqui %@", newPath);

    [[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:nil];

1 个答案:

答案 0 :(得分:7)

您可以获取../user/目录中的所有文件,并将其文件名存储到数组中。然后你可以遍历数组并将文件移动到新目录。

NSString *oldDirectory = [documentsDirectory stringByAppendingPathComponent:@"user"];
NSString *newDirectory = [documentsDirectory stringByAppendingPathComponent:@"leidos"];
NSFileManager *fm = [NSFileManager defaultManager];

// Get all the files at ~/Documents/user
NSArray *files = [fm contentsOfDirectoryAtPath:oldDirectory error:&error];

for (NSString *file in files) {
    [fm moveItemAtPath:[oldDirectory stringByAppendingPathComponent:file]
                toPath:[newDirectory stringByAppendingPathComponent:file]
                 error:&differentError];
}