ios - An efficient way of writing to file, swift -


i'm getting data sensors using bluetooth, want append string of data end of file.

when tried regular approach

if let dir = nssearchpathfordirectoriesindomains(nssearchpathdirectory.documentdirectory, nssearchpathdomainmask.alldomainsmask, true).first {         let path = nsurl(fileurlwithpath: dir).urlbyappendingpathcomponent(self.file)          {             try text.writetourl(path, atomically: false, encoding: nsutf8stringencoding)         }         catch {/* error handling here */} 

my app started slow down until labels not updating anymore.

tried using dispatch_async in background thread still slowing down app.

what approach should use? read sth stream failed find solutions in swift rely on

probably bluetooth reading data faster performing file operations. can optimize appending text file instead of reading content on each write operation. reuse file handler between writes , keep file open.

this sample extracted 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 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)!)     } } 

then, can create single streamer , reuse in different writes:

var mystream = mystreamer() mystream.write("first of all") mystream.write("then after") mystream.write("and, finally") 

in case, have bonus mystreamer outputstreamtype, can use this:

var mystream = mystreamer() print("first of all", tostream: &mystream ) print("then after", tostream: &mystream) print("and, finally", tostream: &mystream) 

finally i'd recommend move 'log.txt' string instance variable , pass constructor parameter:

var mystream = mystreamer("log.txt") 

more info file handler in the apple docs.


Comments