我希望能够在swift中修改我的plist中的值,但是我很难搞清楚它。到目前为止,我可以读取数组中的值,但就是这样。
var playersDictionaryPath = NSBundle.mainBundle().pathForResource("PlayersInfo", ofType: "plist")
var playersDictionary = NSMutableDictionary(contentsOfFile: playersDictionaryPath!)
var playersNamesArray = playersDictionary?.objectForKey("playersNames")? as NSArray
[println(playersNamesArray)][1]
答案 0 :(得分:4)
首先,您无法写入应用资源中的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
代替。
答案 1 :(得分:1)
我找到了怎么做:
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,我没有想到这一点。