0

有人可以告诉我这段代码不起作用吗?在 iOS 6.0 中监视应用程序文档目录时,它总是返回DISPATH_VNODE_WRITE 。(iPad) 下面是我的代码。无论文件被删除、重命名或添加,它总是返回 0x2 :(。这是因为它是我正在监视的目录吗?不是文件!!!有什么办法可以找出导致目录发送通知的原因?

int directoryFileDescripter = open([documentDirectory UTF8String], O_EVTONLY);

if (directoryFileDescripter < 0) {
    NSLog(@"Couldn't obtain file descripter from the system.");
    return;
}

dispatch_queue_t mainQueue = /*dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);*/dispatch_get_main_queue();
if (mainQueue == NULL) {
    NSLog(@"Couldn't obtain mainQueue from the system.");
    close(directoryFileDescripter);
    return;
}

dispSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, directoryFileDescripter, DISPATCH_VNODE_WRITE | DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME, mainQueue);
if (dispSource == NULL) {
    NSLog(@"Couldn't obtain dispatch source for directory from the system.");
    close(directoryFileDescripter);
    return;
}


dispatch_source_set_event_handler(dispSource, ^{

    NSLog(@"directory notification received.");
    int fileDes = dispatch_source_get_handle(dispSource);
    unsigned long mask = dispatch_source_get_data(dispSource);
    char path[PATH_MAX] = {0};
    int nRes = fcntl(fileDes, F_GETPATH, &path);
    if (nRes < 0) {
        return;
    }
if (mask & DISPATCH_VNODE_WRITE) {
        NSLog(@"A file has been written.");
    }

if (mask & DISPATCH_VNODE_DELETE) {
        NSLog(@"A file has been deleted.");
}

if (mask & DISPATCH_VNODE_RENAME) {
        NSLog(@"A file has been renamed.");
}
});

dispatch_source_set_cancel_handler(dispSource, ^{
    close(directoryFileDescripter);
});

dispatch_resume(dispSource);
4

1 回答 1

1

你对“为什么”是正确的。当文件被创建、重命名或删除时,目录会被修改。您正在查看目录,因此您会收到“WRITE”事件。

我通常会通过在每次将目录标记为已写入时重新扫描目录并自己记录更改来处理此问题。如果您不担心目录本身移动或被删除,您可以只关注 WRITE 事件。

您当然也可以查看每个文件的 VNODE,但我希望这对于此类问题的实现会更加复杂。

于 2012-12-06T18:22:00.750 回答