【发布时间】:2019-06-15 19:05:35
【问题描述】:
我是 Swift 和 Xcode 的初学者,正在尝试做简单的数据持久性应用程序。我正在寻找将数组读取和写入文本文件的代码。这个想法是有一个包含一条信息的初始数组。在表格视图加载期间,如果文本文件有数据,则将数据加载到表格视图中。如果没有数据,则显示表格查看数组中的数据。当用户输入数据时,用数组中的数据更改重写文本文件。
我尝试了一些代码,但是每次都遇到文件被重新创建的问题,所以代码不是从文本文件中读取的。
// This function reads from text file and makes the array.
func readDataFromFile(){
let fileURL = dir?.appendingPathComponent(strFileName)
print(fileURL as Any)
//Adding this new as the path seems to change everytime, need fixing here.
let fileManager = FileManager.default
let pathComponent = fileURL!.appendingPathComponent(strFileName)
let filePath = pathComponent.path
if fileManager.fileExists(atPath: filePath){
try allToys = NSMutableArray(contentsOf: fileURL!) as! [String]
}
else
{
writeArrayToFile()
}
}
// This is to write array of data to a file
func writeArrayToFile()
{
let fileURL = dir?.appendingPathComponent(strFileName)
(allToys as NSArray).write(to: fileURL!, atomically: true)
}
期望:每次都从同一个文件中读取数据 实际:每次都会创建一个新的动态路径,所以数据不会被保留。
新代码
让 dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
func writeArrayToFile(){
let fileURL = dir?.appendingPathComponent(fileName)
(allToys as NSArray).write(to: fileURL!, atomically: true)
}
func readDataFromFile(){
let fileURL = dir?.appendingPathComponent(fileName)
let fm = FileManager()
if(fileURL != nil) {
if(!(fm.fileExists(atPath: (fileURL?.path)!))){
let temp = NSMutableArray(contentsOf: fileURL!)
if (temp != nil) {
allToys = NSMutableArray(contentsOf: fileURL!) as! [String]
}
}
}
另外,有没有办法使用相对或绝对路径来代替动态路径?
【问题讨论】:
-
好吧,你在
readDataFromFile中添加了两次strFileName -
嗨 Joakim,感谢您的评论,我更改了代码来执行此操作,但我仍然看到同样的问题。这听起来可能很愚蠢,我无法找到粘贴新代码的方法。
-
添加了新代码 - 仍然是同样的问题.. 有什么建议吗??