xcode 如何快速修改plist

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28888464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:46:18  来源:igfitidea点击:

How to modify plist in swift

xcodeswiftplist

提问by extrablade

I want to be able to modify values from my plist in swift but I'm having trouble figuring it out. So far I can read the values in my array but that's it.

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

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

var playersDictionary = NSMutableDictionary(contentsOfFile: playersDictionaryPath!)

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

[println(playersNamesArray)][1]

回答by Christian

First you can't write to a plist file inside your app resources. So you will need to save your edited plist to another directory. Like your NSDocumentDirectory.

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

As in this answer mentionedyou can get the document-path like that:

正如在这个答案中提到的,您可以获得这样的文档路径:

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

But to answer your question, you can edit an NSMutableDictionarylike that:

但是要回答你的问题,你可以编辑NSMutableDictionary这样的:

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

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

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

If you want to edit your NSArrayon the other hand, you should use an NSMutableArrayinstead.

NSArray另一方面,如果你想编辑你的,你应该使用 an NSMutableArray

回答by extrablade

I found how to do it:

我找到了方法:

    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)

btw, thanks for the NSMutableArray, I wasn't thinking about that.

顺便说一句,感谢 NSMutableArray,我没想过这个。