【问题标题】:Swift cycle which compare times比较时间的快速循环
【发布时间】:2018-06-05 06:27:47
【问题描述】:

我有一个计划时间和当前时间。我应该写比较时间的循环。当计划时间等于当前时间时,周期应该打印或发送通知。

var schedule : String = "12.22.00"
let formatter = DateFormatter()
formatter.dateFormat = "HH.mm.ss"
let calendar = Calendar.current
let minutesago = calendar.date(byAdding: .minute, value: +2, to: Date())!
let res = formatter.string(from: minutesago)

while true {
    if res == schedule {
        notificate()
        print("isequl")
    }
}

【问题讨论】:

  • res 永远不会等于 schedule,因为它们的格式不同,而且值都不会改变。
  • 但都是字符串格式
  • 添加这个:print(res)。注意它与schedule 的不同之处。

标签: swift loops while-loop cycle


【解决方案1】:

这不是一个好的工作方式,但这里对您的代码进行了一些修改:

var schedule : String = "12.19.00"
let formatter = DateFormatter()
formatter.dateFormat = "HH.mm.ss"
while true {
    let date = Date()
    let res = formatter.string(from: date)
    if res == schedule
    {
        print("isequl")
        break
    }
    sleep(10000)
}

您只能获得一次当前时间,因此res == schedule 永远不会是真的。而且您在字符串值中使用了不同的格式。您的字符串是hh.mm.ss,格式化程序是hh.mm

编辑

为此,您应该使用计时器。先获取时间间隔,然后传入Timer为:

let date = Date().addingTimeInterval(interval)
let timer = Timer(fireAt: date, interval: 0, target: self, selector: #selector(runCode), userInfo: nil, repeats: false)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)

【讨论】:

  • 这会阻塞 CPU 而不能真正工作。您必须在每次迭代中睡一段时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
  • 2011-10-02
  • 1970-01-01
相关资源
最近更新 更多