Swift 在使用 NSTimer 时无法输出 [英] Swift cannot output when using NSTimer

查看:43
本文介绍了Swift 在使用 NSTimer 时无法输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 NSTimer 每秒输出到 STDOUT.

I tried output to STDOUT every second by using NSTimer.

我编写了以下代码并将其保存为 sample.swift.

I wrote the following code and saved it as sample.swift.

#!/usr/bin/swift

import AppKit

class Foo : NSObject {
  override init() {
    super.init()
    NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "bar", userInfo: nil, repeats: true)
  }

  func bar() {
    print("buz")
  }
}

let h = Foo()

// Output successful
// while true {
//   print("Foo!")
// }

NSRunLoop.mainRunLoop().run()

然后,我执行了下面的命令,可以看到buz.

Then, I executed the following command and can see buz.

okada@iyokan$ ./sample.swift
buz
buz
buz
buz

所以,我执行了以下命令,但我看不到任何buz.

So, I executed the following command but I cannot see any buz.

okada@iyokan$ ./sample.swift > sample.log # wait 5 seconds
okada@iyokan$ cat sample.log
okada@iyokan$ 

顺便说一下,我尝试了while循环版本(激活注释掉上面的代码)然后我可以通过两个程序获得buz.

By the way, I tried while loop version (activated comment out the above code) then I could get buz by two procedures.

为什么我找不到任何buz?请教我.

Why I could not get any buz? Please teach me.

推荐答案

这是 stdio 库的正常"行为.文件描述符可以缓冲",这意味着所有 printf() 和其他输出操作首先进入内部缓冲区.当那个缓冲区达到一定大小(例如 8KB),将其内容写入实际文件.

That is a "normal" behaviour of the stdio library. A file descriptor can be "buffered", which means that the result of all printf() and other output operations goes to an internal buffer first. When that buffer reaches a certain size (e.g. 8KB), its contents is written to the actual file.

共有三种模式:unbuffered"(所有输出都写入文件立即),行缓冲"(收集输出直到换行字符被打印),和完全缓冲".

There are three modes: "unbuffered" (all output is written to the file immediately), "line buffered" (output is collected until a newline characters is printed), and "fully buffered".

根据 stdout 行是缓冲的、未缓冲的还是不确定的默认?:

Unix 惯例是 stdin 和 stdout 在与终端关联时是行缓冲的,否则为全缓冲(又名块缓冲).

Unix convention is that stdin and stdout are line-buffered when associated with a terminal, and fully-buffered (aka block-buffered) otherwise.

这解释了为什么你看到每个打印操作的输出当输出到达终端时立即,但不是当输出被重定向到一个文件.

This explains why you see the output of each print operation immediately when the output goes to the terminal, but not when output is redirected to a file.

print("buz")
fflush(stdout)

您可以强制将输出立即写入文件.或者,您可以将标准输出设置为行缓冲模式通过调用

you can force the output to be written to the file immediately. Alternatively, you can set standard output into line buffering mode by calling

setlinebuf(stdout)

在打印任何东西之前.

这篇关于Swift 在使用 NSTimer 时无法输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆