快速写入文件的有效方法 [英] An efficient way of writing to file, swift

查看:65
本文介绍了快速写入文件的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用蓝牙从传感器获取数据,我想将获取的数据字符串附加到文件末尾.

I'm getting data from sensors using bluetooth, I want to append the string of data I get to the end of file.

当我尝试常规方法时

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 */}

我的应用开始减速,直到标签不再更新为止.

My app started to slow down until even labels were not updating anymore.

尝试使用 dispatch_async 在后台线程中执行操作,但仍在减慢我的应用程序的速度.

Tried using dispatch_async to do in background thread but still it was slowing down my app.

我应该使用哪种方法?我读了一些关于流的信息,但未能迅速找到我可以依靠的解决方案

What approach should I use? I read sth about stream but failed to find some solutions in swift I could rely on

推荐答案

可能是蓝牙读取数据的速度比执行文件操作的速度快.您可以通过将文本附加到文件而不是在每次写操作中读取所有内容来对其进行优化.您还可以在两次写入之间重用文件处理程序,并使文件保持打开状态.

Probably your bluetooth is reading data faster than you are performing your file operations. You can optimize it by appending the text to the file instead of reading all the content on each write operation. You could also reuse the file handler between writes and keep the file open.

此示例摘自此答案:

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)!)
    }
}

然后,您可以创建一个单一的拖缆,并以不同的方式重复使用它:

Then, you can create a single streamer and reuse it in different writes:

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

在这种情况下,您可以得到 MyStreamer 也是 OutputStreamType 的好处,因此您可以像这样使用它:

In this case, you have the bonus that MyStreamer is also a OutputStreamType, so you can use it like this:

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

最后,我建议您将'log.txt'字符串移动到实例变量,并将其作为构造函数参数传递:

Finally I'd recommend you to move 'log.txt' string to a instance variable and pass it as a constructor parameter:

var myStream = MyStreamer("log.txt")

有关文件处理程序的更多信息,请参见 Apple Docs.

More info about file handler in the Apple Docs.

这篇关于快速写入文件的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆