我正在使用蓝牙从传感器获取数据,我想将获得的数据字符串附加到文件末尾。
当我尝试常规方法时
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 */}
Run Code Online (Sandbox Code Playgroud)
我的应用程序开始变慢,直到标签不再更新。
尝试dispatch_async在后台线程中使用,但它仍然减慢了我的应用程序的速度。
我应该使用什么方法?我阅读了有关流的内容,但未能迅速找到一些我可以依赖的解决方案
可能您的蓝牙读取数据的速度比执行文件操作的速度快。您可以通过将文本附加到文件而不是在每次写入操作时读取所有内容来优化它。您还可以在写入之间重用文件处理程序并保持文件打开。
该样本是从这个答案中提取的:
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)!)
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以创建一个流光并在不同的写入中重用它:
var myStream = MyStreamer()
myStream.write("First of all")
myStream.write("Then after")
myStream.write("And, finally")
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您的奖金MyStreamer也是 a OutputStreamType,因此您可以像这样使用它:
var myStream = MyStreamer()
print("First of all", toStream: &myStream )
print("Then after", toStream: &myStream)
print("And, finally", toStream: &myStream)
Run Code Online (Sandbox Code Playgroud)
最后,我建议您将 'log.txt' 字符串移动到实例变量并将其作为构造函数参数传递:
var myStream = MyStreamer("log.txt")
Run Code Online (Sandbox Code Playgroud)
Apple Docs 中有关文件处理程序的更多信息。
| 归档时间: |
|
| 查看次数: |
3087 次 |
| 最近记录: |