Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify plist in swift

Tags:

xcode

swift

plist

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]
like image 758
extrablade Avatar asked Mar 05 '15 21:03

extrablade


1 Answers

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.

like image 136
Christian Avatar answered Sep 18 '22 16:09

Christian