【问题标题】:DispatchQueue.main.asyncAfter(deadline: ) not working in command line app [duplicate]DispatchQueue.main.asyncAfter(deadline: ) 在命令行应用程序中不起作用 [重复]
【发布时间】:2019-02-27 08:08:07
【问题描述】:

我正在尝试制作一个每秒从 txt 文件中粘贴一个句子的程序。它可以在没有DispatchQueue.main.asyncAfter(deadline: ) 的情况下工作。有了它,它什么也不打印,并立即以退出代码 0 结束。这是程序:

import Cocoa

let file = "slowreadText.txt"
let waitTime: TimeInterval = 1

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

    let fileURL = dir.appendingPathComponent(file)

    do {
        let text = try String(contentsOf: fileURL, encoding: .utf8)
        let sentences = text.components(separatedBy: ".")

        for i in 0..<sentences.count {
            let sentence = sentences[i]
            DispatchQueue.main.asyncAfter(deadline: .now() + (waitTime * Double(i))) {
                print(sentence)
            }
        }

    }catch {
        print(error)
    }
}

【问题讨论】:

  • @ladislas 这行得通,谢谢。

标签: swift cocoa


【解决方案1】:

您需要在脚本末尾调用RunLoop.main.run() 以防止它终止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-01
    • 2015-07-11
    • 2023-01-30
    • 2023-04-08
    • 2019-06-04
    • 2018-02-04
    • 1970-01-01
    • 2020-04-03
    相关资源
    最近更新 更多