【发布时间】:2020-05-31 08:46:00
【问题描述】:
** readData.plist 是:**
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>currentChapter</key>
<string>2</string>
<key>currentLine</key>
<string>2</string>
<key>bookname</key>
<string>ExcelBible</string>
</dict>
</plist>
** 以下为代码:**
let Chapter = currentChapter
let Line = currentLine
let name = bookname
let dict:NSMutableDictionary = NSMutableDictionary()
dict.setObject("1", forKey: "currentChapter" as NSCopying)
dict.setObject("1", forKey: "currentLine" as NSCopying)
dict.setObject("WordBible", forKey: "bookname" as NSCopying)
//I also use dict[0] = "1", and setValue() method both of them are not work
let plistPath = Bundle.main.path(forResource: "readData", ofType: "plist")
dict.write(toFile: plistPath!, atomically: true)
块引用 我这里也使用FileManager和几个例子来保存数据,有的显示“Successfully write”,但是文件没有变化。
块引用
我自 2020 年 2 月 12 日起成为 iOS 开发人员
【问题讨论】:
-
我从.plist读取没问题。
-
您无法写入应用程序包。它是只读的。在 Swift 中不鼓励
NSCoding。在 Swift 中使用PropertyListEncoder并且永远不要使用NSMutable...集合类型。默认情况下,所有本机类型都是可变的variable。并且请遵守命名约定,并以小写字母开头的变量和方法命名。 -
感谢您对PropertyListEncoder和代码编写方法的建议。我更改了我的代码,但它仍然不起作用``` let currentChapter = "10" let currentLine = "10" let nameOfBook = "WordBible" let readData = [currentChapter, currentLine, nameOfBook] // let dataFilePaths = FileManager. default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("gameSave.plist") let data = try PropertyListEncoder().encode(readData) 试试? data.write(到:dataFilePaths,选项:Data.WritingOptions.atomic)```
-
您必须创建一个具有 3 个属性
currentChapter、currentLine和nameOfBook的结构,并将其编码以获得具有相应键的属性列表。 -
你能告诉我为什么我必须使用结构吗?但最后,我必须执行特定的功能。