将UIDocument移动到文件系统上的新位置的正确方法是什么

age*_*fll 6 filesystems uikit nsfilemanager ios5 uidocument

我有一个基于文档的iOS应用程序与UIDocument子类.我需要能够移动它在文件系统上表示的文件.我考虑过用它移动它NSFileManager,但这会弄乱它UIDocumentfileURL财产.关于如何解决这个小难题的任何想法?

Jus*_*oll 5

您可以通过先关闭它来重命名UIDocument,然后在完成处理程序中使用NSFileManager移动文件.成功移动文件后,使用新文件URL初始化UIDocument子类的新实例:

NSURL *directoryURL = [_document.fileURL URLByDeletingLastPathComponent];    
NSFileManager *fileManager = [[NSFileManager alloc] init];    
NSString *filePath = [directoryURL.path stringByAppendingPathComponent:@"NewFileName"];

[_document closeWithCompletionHandler:^(BOOL success) {
    NSError *error;

    if (success)
        success = [fileManager moveItemAtPath:_document.fileURL.path toPath:filePath error:&error];

    if (success) {
        NSURL *url = [NSURL fileURLWithPath:filePath];

        // I handle opening the document and updating the UI in setDocument:
        self.document = [[MyDocumentSubclass alloc] initWithFileName:[url lastPathComponent] dateModified:[NSDate date] andURL:url];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Unable to rename document" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [alert show];
        NSLog(@"Unable to move document: %@", error);
    }
}];
Run Code Online (Sandbox Code Playgroud)


Ell*_*and 5

这可能是旧的,但仍然相关。

您想要做的是以下内容:

移动:使用 NSFileCoordinator 移动文件,在协调器块内,调用

[fileCoordinator itemAtURL:URL willMoveToURL:toURL];
[fileManager moveItemAtURL:newURL toURL:toURL error:&moveError];
[fileCoordinator itemAtURL:URL didMoveToURL:toURL];
Run Code Online (Sandbox Code Playgroud)

删除:覆盖你的 UIDocument 子类或实现文件展示器协议方法accommodatePresentedItemDeletionWithCompletionHandler:来关闭文档。

- (void)accommodatePresentedItemDeletionWithCompletionHandler:(void (^)(NSError *))completionHandler;
{
[self closeWithCompletionHandler:^(BOOL success) {
    NSError *err;
    if (!success)
        err = [NSError error]; // implement your error here if you want

    completionHandler(err);
}];
}
Run Code Online (Sandbox Code Playgroud)

从而确保它能够正确处理被移动的情况。


Con*_*has -1

我在UIDocument类规范(5.1)中找到了这一点:

\n\n
\n

NSFilePresenter协议的实施

\n\n

该类UIDocument采用该NSFilePresenter协议。当另一个客户端尝试读取UIDocument基于 的应用程序的文档时,该读取将暂停,直到该UIDocument对象有机会保存对文档所做的任何更改。

\n\n

尽管某些实现不执行任何操作,但UIDocument实现了所有NSFilePresenter方法。具体来说,UIDocument

\n\n
\n

实现relinquishPresentedItemToReader:将传入块转发到performAsynchronousFileAccessUsingBlock:.

\n\n

实现relinquishPresentedItemToWriter:检查文件修改日期是否已更改;如果文件比以前新,则会revertToContentsOfURL:completionHandler:使用 的值fileURL作为 URL 参数进行调用。

\n\n

实现presentedItemDidMoveToURL:更新 document\xe2\x80\x99s 文件 URL ( fileURL)。

\n\n

在子UIDocument类中,如果重写NSFilePresenter方法,则始终可以调用超类实现 ( super)。

\n
\n
\n\n

我也在绝望地寻找,希望以上内容有所帮助。我还没有测试过 \xe2\x80\x94 我现在就开始尝试。

\n\n

所以基本上,如果我没有错过这里的任何内容,您必须使用移动文档NSFileManager,然后调用presentedItemDidMoveToURL:您的文档。您可能必须使用 来移动文件NSFileCoordinator,以确保不会出现问题。

\n\n

请纠正这个答案中所有错误的地方。我在所有这些方面仍然是个菜鸟。

\n