【问题标题】:Why can't I save data in plist file with Swift为什么我不能使用 Swift 将数据保存在 plist 文件中
【发布时间】: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 个属性 currentChaptercurrentLinenameOfBook 的结构,并将其编码以获得具有相应键的属性列表。
  • 你能告诉我为什么我必须使用结构吗?但最后,我必须执行特定的功能。

标签: ios swift plist


【解决方案1】:

我认为该文件不在可写位置,因此您应该在文档目录中创建它。然后,必须从文档目录中读取它。

【讨论】:

  • 谢谢。我在操场和项目下尝试了 PropertyListEncoder() 方法,它不起作用。
  • 这不是我想的。阅读this
  • 它不起作用,因为我是新开发的。我的朋友帮助我,但他找不到原因。
【解决方案2】:

块引用

我使用了以下代码,但它也不起作用。

块引用


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)

try? data.write(to: dataFilePaths, options: Data.WritingOptions.atomic)

【讨论】:

    猜你喜欢
    • 2014-09-25
    • 2017-05-30
    • 2012-07-05
    • 2022-01-18
    • 2013-03-03
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    相关资源
    最近更新 更多