使用moveItemAtPath将文件夹移动到temp时出现奇怪错误。可可错误516

时间:2012-02-20 13:23:58

标签: objective-c ios nsfilemanager temporary-directory

我尝试将带有文件的文件夹移动到临时文件夹,但我总是收到同样的错误: 该操作无法完成。 (可可错误516。)

这是代码,你觉得有什么奇怪的吗?提前谢谢。

    // create new folder
NSString* newPath=[[self getDocumentsDirectory] stringByAppendingPathComponent:@"algo_bueno"];
NSLog(@"newPath %@", newPath);
if ([[NSFileManager defaultManager] fileExistsAtPath:newPath]) {
    NSLog(@"newPath already exists.");
} else {
    NSError *error;
    if ([[NSFileManager defaultManager] createDirectoryAtPath:newPath withIntermediateDirectories:YES attributes:nil error:&error]) {
        NSLog(@"newPath created.");
    } else {
        NSLog(@"Unable to create directory: %@", error.localizedDescription);
        return;
    }
}

// create a file in that folder
NSError *error;
NSString* myString=[NSString stringWithFormat:@"Probando..."];
NSString* filePath=[newPath stringByAppendingPathComponent:@"myfile.txt"];
if ([myString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
    NSLog(@"File created.");
} else {
    NSLog(@"Failed creating file. %@", error.localizedDescription);
    return;
}

// move this folder and its folder
NSString *tmpDir = NSTemporaryDirectory();
NSLog(@"temporary directory, %@", tmpDir);
if ([[NSFileManager defaultManager] moveItemAtPath:newPath toPath:tmpDir error:&error]) {
    NSLog(@"Movido a temp correctamente");
} else {
    NSLog(@"Failed moving to temp. %@", error.localizedDescription);
}

3 个答案:

答案 0 :(得分:13)

错误516是NSFileWriteFileExistsError

您无法将文件移动到文件已存在的位置:)

(请参阅此处的文档 - https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html并搜索“516”)


更有用的是,您的目标路径应该是文件名,而不是文件夹。试试这个:

// move this folder and its folder
NSString *tmpDir = NSTemporaryDirectory();
NSString *tmpFileName = [tmpDir stringByAppendingPathComponent:@"my-temp-file-name"];
NSLog(@"temporary directory, %@", tmpDir);
if ([[NSFileManager defaultManager] moveItemAtPath:newPath toPath:tmpFileName error:&error]) {
    NSLog(@"Movido a temp correctamente");
} else {
    NSLog(@"Failed moving to temp. %@", error.localizedDescription);
}

答案 1 :(得分:2)

使用以下方法获取唯一的临时文件夹名称:

NSFileManager unique file names

CFUUIDRef uuid = CFUUIDCreate(NULL);
CFStringRef uuidString = CFUUIDCreateString(NULL, uuid);
NSString *tmpDir = [[NSTemporaryDirectory() stringByAppendingPathComponent:(NSString *)uuidString];
CFRelease(uuid);
CFRelease(uuidString);
// MOVE IT
[[NSFileManager defaultManager] moveItemAtPath:myDirPath toPath:tmpDir error:&error]

答案 2 :(得分:0)

moveItemAtPath:toPath:error:的目标路径必须是您正在移动的文件或目录的完整新路径。正如你现在所做的那样,你基本上都试图用你的文件覆盖临时目录本身。

简单修复:

NSString *targetPath = [tmpDir stringByAppendingPathComponent:[newPath lastPathComponent]];
if ([[NSFileManager defaultManager] moveItemAtPath:targetPath toPath: error:&error]) {
   NSLog(@"Moved sucessfully");
}