在swift中写一个文件

时间:2016-03-14 05:21:33

标签: ios swift

这是我在appDelegate中的代码didFinishLaunchingWithOptions()

  var paths : NSArray =  NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    var documentsDirectory = paths.objectAtIndex(0)
    var fileName: String = String(format: "Logger.txt")
    var logFilePath : NSString = documentsDirectory.stringByAppendingPathComponent(fileName)
    freopen(logFilePath, "a+", stderr)

我得到的错误是无法将NSString转换为UnSafepointer。 任何人都可以帮助我如何实现这个?

2 个答案:

答案 0 :(得分:1)

只需从NSString

中删除logFilePath即可
var paths : NSArray =  NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var documentsDirectory = paths.objectAtIndex(0)
var fileName: String = String(format: "Logger.txt")
var logFilePath = documentsDirectory.stringByAppendingPathComponent(fileName)
freopen(logFilePath, "a+", stderr)

更安全的方法就是这样:

let file = "Logger.txt"
let text = "A safer way to do this"

if let directory : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
    let path = directory.stringByAppendingPathComponent(file);

    print(path)

    do {
        try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
    }
    catch {
    }
}

答案 1 :(得分:0)

放开铸造; - )

所有你需要施放的是NSArray来获取objectAtIndex()方法

let paths : NSArray =  NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths.objectAtIndex(0)
let fileName = String(format: "Logger.txt")
let logFilePath = documentsDirectory.stringByAppendingPathComponent(fileName)
freopen(logFilePath, "a+", stderr)

额外奖励:使用let代替var。

编辑:

没有NSArray&的NSString:

let paths =  NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
let fileName = String(format: "Logger.txt")
let logFilePath = NSURL(fileURLWithPath: documentsDirectory).URLByAppendingPathComponent(fileName).absoluteString
freopen(logFilePath, "a+", stderr)