age*_*fll 6 filesystems uikit nsfilemanager ios5 uidocument
我有一个基于文档的iOS应用程序与UIDocument
子类.我需要能够移动它在文件系统上表示的文件.我考虑过用它移动它NSFileManager
,但这会弄乱它UIDocument
的fileURL
财产.关于如何解决这个小难题的任何想法?
您可以通过先关闭它来重命名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)
这可能是旧的,但仍然相关。
您想要做的是以下内容:
移动:使用 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\n\n
NSFilePresenter
协议的实施该类
\n\nUIDocument
采用该NSFilePresenter
协议。当另一个客户端尝试读取UIDocument
基于 的应用程序的文档时,该读取将暂停,直到该UIDocument
对象有机会保存对文档所做的任何更改。尽管某些实现不执行任何操作,但
\n\nUIDocument
实现了所有NSFilePresenter
方法。具体来说,UIDocument
:\n\n实现
\n\nrelinquishPresentedItemToReader:
将传入块转发到performAsynchronousFileAccessUsingBlock:
.实现
\n\nrelinquishPresentedItemToWriter:
检查文件修改日期是否已更改;如果文件比以前新,则会revertToContentsOfURL:completionHandler:
使用 的值fileURL
作为 URL 参数进行调用。实现
\n\npresentedItemDidMoveToURL:
更新 document\xe2\x80\x99s 文件 URL (fileURL
)。在子
\nUIDocument
类中,如果重写NSFilePresenter
方法,则始终可以调用超类实现 (super
)。
我也在绝望地寻找,希望以上内容有所帮助。我还没有测试过 \xe2\x80\x94 我现在就开始尝试。
\n\n所以基本上,如果我没有错过这里的任何内容,您必须使用移动文档NSFileManager
,然后调用presentedItemDidMoveToURL:
您的文档。您可能必须使用 来移动文件NSFileCoordinator
,以确保不会出现问题。
请纠正这个答案中所有错误的地方。我在所有这些方面仍然是个菜鸟。
\n 归档时间: |
|
查看次数: |
2591 次 |
最近记录: |