NSTask输出到文本视图有时会转到控制台

时间:2016-01-21 06:07:21

标签: swift nstextview nstask

将NSTask对象的输出定向到文本视图适用于我尝试过的大多数命令,但不适用于git clone。在那个例子中,输出进入Xcode控制台,即使我的代码中没有打印语句。下面写的代码进入控制台。如果我改为使用注释掉的行,则输出将转到文本视图。

    var cloneTask: NSTask!
    @IBOutlet var tv: NSTextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        cloneTask = NSTask()
        cloneTask.launchPath = "/usr/bin/git"
        cloneTask.arguments = ["clone", "https://github.com/edelmar/DHT22_Reader"]
        //cloneTask.launchPath = "/usr/bin/env"
        //cloneTask.arguments = ["pwd"]
        cloneTask.pipeOutputTo(tv)
        cloneTask.launch()
    }

pipeOutputTo:是NSTask上的扩展函数,

extension NSTask {
    func pipeOutputTo(logger: AnyObject) -> AnyObject {
        let pipe = NSPipe()
        self.standardOutput = pipe

        let stdoutHandle = pipe.fileHandleForReading
        stdoutHandle.waitForDataInBackgroundAndNotify()
        let observer = NSNotificationCenter.defaultCenter().addObserverForName(NSFileHandleDataAvailableNotification, object: stdoutHandle, queue: nil) { _ in
            let dataRead = stdoutHandle.availableData
            let stringRead = NSString(data: dataRead, encoding: NSUTF8StringEncoding)
            logger.append(stringRead as! String)
            if stringRead!.length > 0 {
                stdoutHandle.waitForDataInBackgroundAndNotify()
            }
        }
        return observer
    }
}

有谁知道行为不同的原因?

0 个答案:

没有答案