【问题标题】:How to modify plist in swift如何在swift中修改plist
【发布时间】:2015-05-07 10:46:14
【问题描述】:

我希望能够快速修改我的 plist 中的值,但我无法弄清楚。到目前为止,我可以读取数组中的值,仅此而已。

var playersDictionaryPath = NSBundle.mainBundle().pathForResource("PlayersInfo", ofType: "plist")

var playersDictionary = NSMutableDictionary(contentsOfFile: playersDictionaryPath!)

var playersNamesArray = playersDictionary?.objectForKey("playersNames")? as NSArray

[println(playersNamesArray)][1]

【问题讨论】:

  • 如果plist 是捆绑包的一部分,则不能;但如果你将它复制到Documents 文件夹中,你可以在那里更新它。

标签: xcode swift plist


【解决方案1】:

首先,您不能写入应用资源中的 plist 文件。因此,您需要将编辑后的 ​​plist 保存到另一个目录。喜欢你的NSDocumentDirectory

As in this answer mentioned 你可以这样获取文档路径:

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString

但要回答您的问题,您可以像这样编辑NSMutableDictionary

//add entries:
playersDictionary.setValue("yourValue", forKey: "yourKey")

//edit entries:
playersDictionary["yourKey"] = "newValue" //Now has value 'newValue'

//remove entries:
playersDictionary.removeObjectForKey("yourKey")

另一方面,如果您想编辑 NSArray,则应改用 NSMutableArray

【讨论】:

  • 我们无法写入包中的自定义 plist?
【解决方案2】:

我找到了方法:

    var playersDictionaryPath = NSBundle.mainBundle().pathForResource("PlayersInfo", ofType: "plist")

    var playersDictionary = NSMutableDictionary(contentsOfFile: playersDictionaryPath!)

    var playersNamesArray = playersDictionary?.objectForKey("playersNames")? as NSMutableArray

    //this is a label I have called player1Name
    playersNamesArray[0] = "\(player1Name.text)"

    playersDictionary?.writeToFile(playersDictionaryPath!, atomically: true)

顺便说一句,感谢 NSMutableArray,我没想到。

【讨论】:

  • 可以在 info.plist 文件中编辑后台功能吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多