2016-03-14 173 views
1

文件這是我的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。 任何人都可以幫助我,我應該如何實施這個?

回答

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) 
1

剛從logFilePath刪除NSString

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 { 
    } 
}