我是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]
}
}
}另外,有没有办法使用相对路径或绝对路径而不是动态路径?
发布于 2019-06-16 15:36:29
一个问题是,您试图仅在文件不存在时才读取该文件,if(!(fm.fileExists
由于我在重写和尝试理解代码时意识到了这一点,所以我也可以发布我的代码版本。请注意,由于我没有完全理解您的类/结构定义,我通过使用参数和返回值而不是属性来使函数更加独立
我跳过了dir作为属性,将它变成了一个局部变量,下面是我的write函数
func write(_ array: [Any], toFile fileName: String){
guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
fatalError("No Document directory found")
}
let fileUrl = dir.appendingPathComponent(fileName)
(array as NSArray).write(to: fileUrl, atomically: true)
}并且通过不使用FileManager简化了读取功能
func read(_ fromFile: String) -> [String]? {
guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
fatalError("No Document directory found")
}
let fileUrl = dir.appendingPathComponent(fromFile)
if let temp = NSArray(contentsOf: fileUrl) {
return temp as? [String]
}
return nil
}测试代码
let fileName = "toys.txt"
var allToys = ["Duck", "Playstation", "iPhone"]
write(allToys, toFile: fileName)
if let saved = read(fileName) {
allToys = saved
allToys.append("Lego")
write(allToys, toFile: fileName)
}https://stackoverflow.com/questions/56613372
复制相似问题