swift - 为什么我不能在 swift 中的 for 循环中观看多个文件?

标签 swift cocoa

我正在使用 DispatchSource API 来观察 macOS 应用程序中文件系统的更改。当我一项一项地执行它时,它可以工作,但是当我在 for in 循环中执行它时,它不起作用。为什么会这样?它们不是一样吗?

这不起作用,文件描述符是正确的,但永远不会调用 setEventHandler

func watch(onFsChange: @escaping () -> Void) {

        for fileDescriptor in self.fileDescriptors {
            source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fileDescriptor, eventMask: fsEvent, queue: queue)

            source?.setEventHandler {
                FSWatcher.updateStatus()
                onFsChange()
            }

            source?.setCancelHandler {
                close(fileDescriptor)
            }

            source?.resume()
        }

    }

这是有效的,当路径发生任何变化时会调用setEventHandler

func watch(onFsChange: @escaping () -> Void) {

        source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: self.fileDescriptors[0], eventMask: fsEvent, queue: queue)

        source?.setEventHandler {
            FSWatcher.updateStatus()
            onFsChange()
        }

        source?.setCancelHandler {
            close(self.fileDescriptors[0])
        }

        source?.resume()



        source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: self.fileDescriptors[1], eventMask: fsEvent, queue: queue)

        source?.setEventHandler {
            FSWatcher.updateStatus()
            onFsChange()
        }

        source?.setCancelHandler {
            close(self.fileDescriptors[1])
        }

        source?.resume()


    }

最佳答案

您正在重新分配您的 source新属性(property)DispatchSourceFileSystemObject每次,尽管先前分配的源都会被释放。我建议在第一种情况下,最后一个 fileDescriptor 指向从未更改过的内容,而在第二种情况下,fileDescriptors[1] 则指向经常更改的内容。
决定是var sources = [DispatchSourceFileSystemObject]()而不是单个源属性,并在函数循环内添加源,如下所示:

let source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fileDescriptor, eventMask: fsEvent, queue: queue)
sources.append(source)

关于swift - 为什么我不能在 swift 中的 for 循环中观看多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50869944/

相关文章:

swift 3 : TPKeyboardAvoidingScrollView not working properly on one UITextField in UITableViewCell

ios - 从另一个应用程序打开时,在 applicationWillTerminate 之后以首选状态打开应用程序?

json - SwiftyJSON 遍历 JSON 对象数组

swift - 由于抛出的异常,让 Swift 相信函数永远不会返回

macos - 从模板打开无标题文档

objective-c - Cocoa/Objective-C 中的简单字符串解析 : parsing a command line into command and arguments

cocoa - NSTimer 永远不会启动

ios - UIScrollView 与 UITextField/UIPickerView 的奇怪行为

objective-c - NSOpenPanel 在全屏 NSWindow 之上?

cocoa - Swift 中的 FSMountServerVolumeSync 发生了什么?