objective-c - NSFileCoordinator coordinateWritingItemAtURL 的长时间延迟

标签 objective-c cocoa nsfilecoordinator nsfilepresenter

我正在我的应用程序中设置 NSFileCoordinatorNSFilePresenter,这样我就可以安全地从我的 AppleWatch 应用程序执行文件 IO。在我的代码中的某些地方,我快速连续地向文件写入了几次。这本身就是一个问题,我正在努力纠正它,但我注意到这个过程中有一些奇怪的行为。

我这样写我的文章:

//In a class that implements NSFilePresenter:
NSFileCoordinator *coord = [[NSFileCoordinator alloc]initWithFilePresenter:self];
[coord coordinateWritingItemAtURL:self.presentedItemUrl options:0 error:nil byAccessor:^(NSURL *url)
{
  //do my writing here using CFWriteStreamRef or NSOutputStream
}];

在第一次写入时,写入 block 在 1 毫秒内发生。但在那之后,调用 coordinateWritingItemAtURL 和执行写入 block 之间大约有 0.5 秒的延迟。

这是预期的行为吗?

Some of the documentation对于 NSFileCoordinatorNSFilePresenter 说要使用 prepareForReadingItemsAtURLs:writingItemsAtURLs:options:error:byAccessor: 进行批处理操作,但是得到这样的一个似乎很奇怪当我不批处理时会延迟很长时间。

更新:阅读也会发生这种情况。

更新 2: Here是重现问题的示例项目。

更新 3:使用此 API 协调应用程序及其扩展程序是 apparently一个bad idea .但问题仍然存在。

最佳答案

引用 File System Programming Guide ,您可以阅读以下内容:

you might want to avoid incorporating changes directly from your file presenter method. Instead, dispatch a block asynchronously to a dispatch queue and process the changes at a later time. This lets you process the changes at your app’s convenience without causing unnecessary delays to the file coordinator that initiated the change. Of course, when saving or relinquishing control of a file (such as in the relinquishPresentedItemToReader:, relinquishPresentedItemToWriter:, or savePresentedItemChangesWithCompletionHandler: methods) you should perform all necessary actions immediately and not defer them.

我认为这是您推迟操作的情况。

可能的解决方案:

请阅读 this 好吧,要正确处理多个连续的写入操作, relinquishPresentedItemToWriter ,可以完成这项工作,同样适用于读取文件, relinquishPresentedItemToReader ,假设多个不同的对象正在尝试读取和写入同一个文件。

附言:

我不知道你的应用程序到底做了什么,但我希望你已经阅读了这个:

If you are implementing a document-based app, you do not need to incorporate file presenter semantics into your NSDocument subclasses. The NSDocument class already conforms to the NSFilePresenter protocol and implements the appropriate methods. Thus, all of your documents automatically register themselves as presenters of their corresponding file and do things like save changes and track changes to the document.

关于objective-c - NSFileCoordinator coordinateWritingItemAtURL 的长时间延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29679019/

相关文章:

ios - 键值观察外观类上的静态 NSDictionary

ios - 在 sprite kit Xcode 中创建一个整数数组

ios - 实现级联删除的Realm最佳实践

objective-c - NSFilePresenter -presentedSubitemDidAppearAtURL : method never gets called

ios - 重命名 iCloud 文档

iphone - 当我尝试使用 b2Body 的功能时游戏崩溃了——为什么?

cocoa - 用于触摸屏应用程序的屏幕键盘

cocoa - 更改 NSCollectionView 的选择行为

cocoa - 如何使用 OS X 的辅助功能 API 为我的应用程序编写验收测试?

objective-c - 永远不会调用 NSFilePresenter 方法