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

Ric*_*rdo 5 objective-c temporary-directory nsfilemanager ios

我尝试将带有文件的文件夹移动到临时文件夹,但我总是收到相同的错误:操作无法完成.(可可错误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);
}
Run Code Online (Sandbox Code Playgroud)

dea*_*rne 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);
}
Run Code Online (Sandbox Code Playgroud)