将打印重定向到文件,如将NSLog重定向到文件

Dur*_*n.H 4 nslog ios swift

我已使用宏将NSLog重定向到文件.

但我无法迅速找到一种稳定的方法来做到这一点.

截至目前,我正在做一个解决方法

我定义了以下方法,所以无论何时我在文件中调用print它都来到这里并将其写入文件.

func print(log:String!) {
        if let logg = log {
            DeveloperConsoleManager.sharedInstance.writeOnConsoleLog(logg)
        }
    }
Run Code Online (Sandbox Code Playgroud)

但这种方法的问题是

如果我愿意,我会在电话中获得额外的参数

print("some comments",Obj1,Obj2)
Run Code Online (Sandbox Code Playgroud)

所以我必须这样使用

print("some comments \(Obj1) \(Obj2)")
Run Code Online (Sandbox Code Playgroud)

2.我会得到错误,如无法将'[AnyObject]'类型的值转换为预期的参数类型'String!' 如果我尝试直接打印对象

print(obj)
Run Code Online (Sandbox Code Playgroud)

所以我必须调用对象的描述方法

print(obj.description)
Run Code Online (Sandbox Code Playgroud)

3. 我必须在上面引用的功能定义中包含我想要的功能但在NSLog的情况下,它在一个地方全局定义

所以现在我正在寻找一个稳定的解决方案,将swift中的print内容重定向到文件中

所以我可以像往常一样快速使用印刷品

更新:

我尝试覆盖打印但我得到的 方法不会覆盖其超类中的任何方法

Rob*_*ier 6

首先,NSLog用宏覆盖是非常糟糕的方法.只需使用不同的函数名称并使用它.压倒性print更加脆弱.只需将其他名称命名即可.当有人看到NSLogprint在代码中,它应该不是一个技巧.

也就是说,只要你给它正确的签名,它通常可以在给定的模块中工作:

public func print(items: Any..., separator: String = "", terminator: String = "\n")
Run Code Online (Sandbox Code Playgroud)

(编辑:修正了签名,确切地说明了它是如何print做的,而不仅仅是显示文档.)

您没有...在函数中使用varargs语法(),这就是它不接受多个参数的原因.如果你想让它接受非字符串(比如obj)那么你必须接受Any,而不仅仅是String.

如果您只是制作自己的printlog功能(或任何您想要的功能),那么您当然可以使用任何方便的签名,但如果您要重载print,则需要匹配其签名和功能.

这是完整的实施.这是一种可怕的方式.你不应该覆盖print.但这就是Swift允许它完成的方式(分散在三个文件中只是为了证明它正在工作):

main.swift:

func print(items: Any..., separator: String = "", terminator: String = "\n") {
    Swift.print("My print is printing \(items)", separator: separator, terminator: terminator)
}

print("In main!")
file1print()
file2print()
Run Code Online (Sandbox Code Playgroud)

file1.swift:

func file1print() {
    print("file1!") // Calls our print
}
Run Code Online (Sandbox Code Playgroud)

file2.swift:

func file2print() {
    print("file2!") // Calls our print
}
Run Code Online (Sandbox Code Playgroud)

再次,这是一个可怕的想法.只需创建一个新功能,它就会更好,更灵活,更清晰.但斯威夫特绝对可以做到.

请注意,如果您的真正目标只是将stdout或stderr写入文件,则无需以这种方式覆盖print或NSLog.只需重新打开你的stdout和/或stderr.例如:

let path: NSString = ...;
freopen(path.UTF8String, "a+", stderr)
Run Code Online (Sandbox Code Playgroud)

这将重定向stderr.使用stdout获取stdout.这适用于打印到stdout/err的任何内容,无论它是什么模块.