我使用GCD监控我的应用文档文件夹中的传入文件。但是问题是我的通知在文件写入开始时触发,这导致然后处理该文件的类失败,因为它正在查看不完整的文件。我想要的是在文件写入事件完成后触发的通知。我查看了DISPATCH_VNODE定义,但它们似乎都没有匹配。我怎么能这样做?我不太热衷于低级文件系统的东西,但是有一个" hold"或者在写入文件时放在文件上的东西?如果是这样,我可以监控该保留何时释放?以下是我用于监视文件系统事件的方法。
if (_src != NULL) return;
// Fetch pathname of the directory to monitor
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
if (!docPath) return;
// Open an event-only file descriptor associated with the directory
int dirFD = open([docPath fileSystemRepresentation], O_EVTONLY);
if (dirFD < 0) return;
// Get the main thread's serial dispatch queue (since we'll be updating the UI)
dispatch_queue_t queue = dispatch_get_main_queue();
if (!queue)
{
close(dirFD);
return;
}
// Create a dispatch source to monitor the directory for writes
_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, // Watch for certain events on the VNODE spec'd by the second (handle) argument
dirFD, // The handle to watch (the directory FD)
DISPATCH_VNODE_WRITE, // The events to watch for on the VNODE spec'd by handle (writes)
queue); // The queue to which the handler block will ultimately be dispatched
if (!_src)
{
close(dirFD);
return;
}
// Set the block to be submitted in response to an event
dispatch_source_set_event_handler(_src, ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"New File Added" object:nil];
});
// Set the block to be submitted in response to source cancellation
dispatch_source_set_cancel_handler(_src, ^{close(dirFD);});
// Unsuspend the source s.t. it will begin submitting blocks
dispatch_resume(_src);