Ios 未使用字符串';将文本写入文件;s";写下;实例方法
这段代码在我的viewDidLoad()方法中完美地将“Hello”写入“test2.csv”。但是,当我在另一个名为getInsightResult()的方法(我在viewDidLoad中调用)中运行代码摘录时,正在编写的文本是空白的。但是,当我打印文本时,它不是空的,而是显示正确的文本Ios 未使用字符串';将文本写入文件;s";写下;实例方法,ios,swift,Ios,Swift,这段代码在我的viewDidLoad()方法中完美地将“Hello”写入“test2.csv”。但是,当我在另一个名为getInsightResult()的方法(我在viewDidLoad中调用)中运行代码摘录时,正在编写的文本是空白的。但是,当我打印文本时,它不是空的,而是显示正确的文本 var file = "" var text = "" var path: URL? override viewDidLoad(){ super.viewDidLoad() file =
var file = ""
var text = ""
var path: URL?
override viewDidLoad(){
super.viewDidLoad()
file = "test2.csv" //this is the file I will write to
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
path = dir.appendingPathComponent(file)
do {
text = "Hello"
try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
}
catch {/* error handling here */}
}
getInsightResult()
}
这个问题仅仅是您的一个误解:您似乎认为String的
write
方法会附加到一个现有的文件中,而它不会。它将替换文件的内容
因此,您的代码工作得非常完美。每次您说text.write…
时,文本都会写入文件。“问题”在于这一行:
func getInsightResult() {
for x in 0...4{
for y in 0...4{
if(y != 3){
do{
let temp = arrayOfDataArrays[y]
text = String(temp[x])
print("Tester:\(temp[x])")
print("Text:" + text)
try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
}
catch {/* error handling here */}
}
}
text = "\n"
do{try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)}
catch {/* error handling here */}
}
}
…使用单个换行符替换文件中的所有内容。由于这是执行的最后一行,这就是我们完成时文件的状态。这个问题仅仅是您的一个误解:您似乎想象String的
write
方法附加到现有文件,而它没有。它将替换文件的内容
因此,您的代码工作得非常完美。每次您说text.write…
时,文本都会写入文件。“问题”在于这一行:
func getInsightResult() {
for x in 0...4{
for y in 0...4{
if(y != 3){
do{
let temp = arrayOfDataArrays[y]
text = String(temp[x])
print("Tester:\(temp[x])")
print("Text:" + text)
try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
}
catch {/* error handling here */}
}
}
text = "\n"
do{try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)}
catch {/* error handling here */}
}
}
…使用单个换行符替换文件中的所有内容。因为这是执行的最后一行,所以这是我们完成时文件的状态。试试这个
text = "\n"
do{try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)}
试试这个
text = "\n"
do{try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)}
是否有方法附加到现有文件?这就是我试图做的,最终结果,只需搜索“iOS文本文件附加”或类似内容。或者将所有内容累积到一个字符串中,然后写出该字符串,一次。不是每次都设置
text
,而是每次都追加到text
;然后将文本
写入一个文件,一次,在文件的最后。好吧,我正试图以一种特定的方式格式化我的CSV文件,并将其附加到文本
字符串将非常复杂。是否有方法附加到现有文件?这就是我试图做的,最终结果,只需搜索“iOS文本文件附加”或类似内容。或者将所有内容累积到一个字符串中,然后写出该字符串,一次。不是每次都设置text
,而是每次都追加到text
;然后将text
写入一个文件,一次,最后一次。好的,我正在尝试以特定的方式格式化我的CSV文件,并将其附加到文本
字符串将非常复杂。请解释问题中的代码有什么问题,并解释您的答案如何解决问题。请解释问题中的代码有什么问题,以及解释您的答案如何解决问题。有关详细信息,请参阅正在向文件追加文本。有关向文件追加文本的信息,请参阅。