文件大小更新时,不会调用监视目录更改的DispatchSource

moh*_*hak 5 filesystems ios swift

我编写了UITableViewController的子类,该子类列出了一组目录中的文件以及它们各自的大小。当这些目录中有任何更改时,它也会自动更新。该类用于DispatchSource“监视”目录。这是执行此操作的代码:

    for dir in directories {
        let fd = dir.withUnsafeFileSystemRepresentation { (filenamePointer) -> Int32 in
            // vfw_open is a wrapper function for open()
            return vfw_open(filenamePointer, O_EVTONLY)
        }

        guard fd != 0 else {
            return
        }

        let watcher = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd,
                                                                 eventMask: DispatchSource.FileSystemEvent.write,
                                                                 queue: DispatchQueue.global(qos: .utility))

        watcher.setEventHandler { [weak self] in
            DispatchQueue.main.async {
                self?.updateFileList()
            }
        }

        watcher.setCancelHandler() {
            close(fd)
        }

        watcher.resume()
    }
Run Code Online (Sandbox Code Playgroud)

这段代码基本上将观察者添加到每个目录中,并updateFileList在观察到更改时进行调用。它运行完美,并且我的文件列表几乎随时随地更新。问题是,当我将大文件复制到目录时,updateFileList立即被调用。因此,我的控制器将新文件的大小显示为0字节。但之后该文件被完全复制,updateFileList不是叫,因此该文件的实际大小不会更新。如何获取要更新的文件大小?

Rob*_*ier 4

当您向目录添加监视程序时,您正在监视目录本身,而不是目录中的文件。目录只是文件列表。当该列表发生更改(创建、删除文件或移入或移出文件)时,目录就会更改,并且您的观察程序将被调用。对文件内容的更改不会修改目录。

要监视文件的更改,您必须为该文件添加监视程序。

  • 这是一个示例,如何做到这一点:https://github.com/varuzhnikov/HelloWorld/blob/master/RSTDirectoryMonitor.m (3认同)