Странная ошибка при перемещении папки в temp с помощью moveItemAtPath. Какао ошибка 516 - PullRequest
5 голосов
/ 20 февраля 2012

Я пытаюсь переместить папку с файлом во временную папку, но всегда получаю одну и ту же ошибку: операция не может быть завершена.(Ошибка какао 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 ]

13 голосов
/ 20 февраля 2012

Ошибка 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);
}
2 голосов
/ 06 мая 2012

Получить уникальное имя временной папки, используя следующий метод:

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]
0 голосов
/ 06 мая 2012

Целевой путь для moveItemAtPath:toPath:error: должен быть полным новым путем к файлу или каталогу, который вы перемещаете. Делая это сейчас, вы пытаетесь перезаписать сам временный каталог своим файлом.

Простое исправление:

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