2016-08-01 42 views
2

我從使用藍牙的傳感器獲取數據,我想追加到達文件末尾的數據字符串。寫入文件的有效方法swift

當我試圖常規方法

if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first { 
     let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(self.file) 

     do { 
      try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding) 
     } 
     catch {/* error handling here */} 

我的應用程序開始放緩,直到連標籤都沒有更新了。

嘗試使用dispatch_async做後臺線程,但它仍然是放緩我的應用程序。

我應該使用什麼方法?我讀了一些關於流的信息,但未能找到一些解決方案,我可以依靠

+0

你爲什麼要閱讀所有內容每次寫入文件的文件?你可以寫在文件末尾 – redent84

+0

如果你可以提供一個示例,我應該怎麼做 – DCDC

+0

你應該試試這個庫,使它更簡單:https://github.com/nvzqz/FileKit – MCMatan

回答

3

也許您的藍牙讀取數據的速度比您執行文件操作的速度要快。您可以通過將文本附加到文件而不是讀取每個寫入操作上的所有內容來對其進行優化。您也可以在寫入之間重用文件處理程序並保持文件處於打開狀態。

這個樣品是從this answer提取:

struct MyStreamer: OutputStreamType { 
    lazy var fileHandle: NSFileHandle? = { 
     let fileHandle = NSFileHandle(forWritingAtPath: self.logPath) 
     return fileHandle 
    }() 

    lazy var logPath: String = { 
     let path : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first! 
     let filePath = (path as NSString).stringByAppendingPathComponent("log.txt") 

     if !NSFileManager.defaultManager().fileExistsAtPath(filePath) { 
      NSFileManager.defaultManager().createFileAtPath(filePath, contents: nil, attributes: nil) 
     } 
     print(filePath) 
     return filePath 

    }() 

    mutating func write(string: String) { 
     print(fileHandle) 
     fileHandle?.seekToEndOfFile() 
     fileHandle?.writeData(string.dataUsingEncoding(NSUTF8StringEncoding)!) 
    } 
} 

然後,您可以創建一個流光並在不同的寫重用:

var myStream = MyStreamer() 
myStream.write("First of all") 
myStream.write("Then after") 
myStream.write("And, finally") 

在這種情況下,你有獎金是MyStreamer也是OutputStreamType,所以你可以這樣使用它:

var myStream = MyStreamer() 
print("First of all", toStream: &myStream) 
print("Then after", toStream: &myStream) 
print("And, finally", toStream: &myStream) 

最後我建議你移動「log.txt的」字符串到實例變量,並把它作爲一個構造函數參數:有關文件處理程序

var myStream = MyStreamer("log.txt") 

更多信息在the Apple Docs

+0

非常感謝,稍後會再檢查一次,並告訴你結果! :) – DCDC

+0

太神奇了,謝謝! – DCDC

0

嘗試寫入文件,這樣的..

var paths: [AnyObject] = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) 
let filePath = paths[0].stringByAppendingString("/filename.mov") 

do 
    { 
    try NSFileManager.defaultManager().removeItemAtURL(outputURL) 
    } 
catch 
    { 

      error as NSError 
    } 

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

我的意思是最後要說的是,你必須先刪除。如果有任何疑問,你可以問我

相關問題