2017-03-03 83 views
2

我正在使用手機記錄一些傳感器數據,並通過SQLKit通過SharkORM(DBAccess)將其存儲在設備上。Swift:Streaming /撰寫CSV文件

我現在想將這些數據寫入CSV文件,但是現在我已經達到了160萬條記錄。

目前,我正在循環1000條記錄,將它們添加到一個字符串,並在最後寫出它們。但是,一定有更好的方法來做到這一點?

func writeRawFile() 
    { 
     let fileName = "raw" 
     let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) 

     let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("csv") 

     var data = "time,lat,lon,speed,x_acc,y_acc,z_acc,gyro_x,gyro_y,gyro_z,compass,orientation\r\n" 

     let count = RawReading.query().count() 
     var counter = 0; 
     let df = DateFormatter() 
     df.dateFormat = "y-MM-dd H:m:ss.SSSS" 

     for i in stride(from:0, to: count, by: 1000) 
     { 
      autoreleasepool { 

       for result in RawReading.query().offset(Int32(i)).limit(1000).fetch() 
       { 
        if let raw : RawReading = result as? RawReading 
        { 
         if (Double(raw.speed!) > 3.0) //1 Meter per Second = 2.236936 Miles per Hour 
         { 
          //print(df.string(from: raw.date!)) 

          data += "\(df.string(from: raw.date!)),\(raw.lat!),\(raw.lon!),\(raw.speed!),\(raw.x!),\(raw.y!),\(raw.z!),\(raw.xx!),\(raw.yy!),\(raw.zz!),\(raw.compass!),\(raw.orientation!)" + "\r\n" 

          counter += 1 
         } 

        } 
       } 

       print ("Written \(i) of \(count)") 

      } 
     } 

     print("Count \(count) \(counter)") 

     //write the file, return true if it works, false otherwise. 
     do{ 
      try data.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8) 
     } catch{ 
      print("error") 
     } 
    } 

回答

5

打開用於寫入的FileHandle,然後生成並分別寫每一行,這樣你就不必保持整個文件的內容 內存:

do { 
    let file = try FileHandle(forWritingTo: fileURL) 
    defer { file.closeFile() } 

    for <... your loop ...> { 
     let line = ... // build one CSV line 
     file.write(line.data(using: .utf8)!) 
    } 

} catch let error { 
    // ... 
} 

你也可以寫首先是一個臨時文件,然後將其重命名爲 實際文件,以避免 出錯時出現損壞的文件。