5

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.

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

var playersDictionary = NSMutableDictionary(contentsOfFile: playersDictionaryPath!)

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

[println(playersNamesArray)][1]
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
extrablade
  • 363
  • 1
  • 3
  • 16
  • if the `plist` is part of the bundle, you can't; but if you copy it into the `Documents` folder and you can update it there. – holex Mar 06 '15 at 11:51

2 Answers2

6

Firstly, 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.

As in this answer mentioned you 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 NSMutableDictionary like that:

//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 NSArray on the other hand, you should use an NSMutableArray instead.

Amol M Kulkarni
  • 21,143
  • 34
  • 120
  • 164
Christian
  • 22,585
  • 9
  • 80
  • 106
3

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.

extrablade
  • 363
  • 1
  • 3
  • 16