5

ファイルを含むフォルダーを一時フォルダーに移動しようとしましたが、常に同じエラーが表示されます:操作を完了できませんでした。(ココア エラー 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);
}
4

3 に答える 3

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);
}
于 2012-02-20T13:28:05.637 に答える
2

次の方法を使用して、一意の一時フォルダー名を取得します。

NSFileManager の一意のファイル名

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]
于 2012-05-06T01:24:24.080 に答える
0

ターゲット パスmoveItemAtPath:toPath:error:は、移動するファイルまたはディレクトリの完全な新しいパスである必要があります。現在行っているように、基本的には一時ディレクトリ自体をファイルで上書きしようとしています。

簡単な修正:

NSString *targetPath = [tmpDir stringByAppendingPathComponent:[newPath lastPathComponent]];
if ([[NSFileManager defaultManager] moveItemAtPath:targetPath toPath: error:&error]) {
   NSLog(@"Moved sucessfully");
}
于 2012-05-06T01:42:27.073 に答える