I would like to save some configuration data to my plist file which contains arrays and regular variable types. It looks like this:
(http://s10.postimg.org/f2xpgur1l/plist.png) (sorry I can not attach any image)
My function which do this looks like so:
// Saves the data into a plist file
func saveObject(i_fileName: String, i_keyForValueToSave: String, i_valueToSave: String, i_keyForXInitializer:String, i_valueXInitializer: String) {
var fileName: String = i_fileName
var keyForValueToSave: String = i_keyForValueToSave
var valueToSave: AnyObject = i_valueToSave
var keyForXInitializer: String = i_keyForXInitializer
var valueXInitializer: String = i_valueXInitializer
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as! NSString
let path = documentsDirectory.stringByAppendingPathComponent(fileName)
var dict: NSMutableDictionary = [keyForXInitializer: valueXInitializer]
//saving values
dict.setObject(valueToSave, forKey: keyForValueToSave)
//writing to plist
dict.writeToFile(path, atomically: false)
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
println("Saved Data.plist file is --> \(resultDictionary?.description)")
}
And I call it like so:
saveObject("Selection.plist", "Item 0", "testConfig, "Item 3", "XInitializerItem_01")
The result looks then like so:
(http://s13.postimg.org/kbq103707/result.png) (sorry I can not attach any image)
As you can see, the "testConfig" which should be saved into an array will be saved as a normal string in the pilst file. Which is not the goal for me. Every item I would like to add to this array. Im really new in SWIFT and Im a but stuck in space. Any help would be great! thank you!
The code below creates the plist you need, you just need to populate the values correctly to match your needs
func saveObject(i_fileName: String, i_keyForValueToSave: String, i_valueToSave: String, i_keyForXInitializer:String, i_valueXInitializer: String) {
var fileName: String = i_fileName
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as! NSString
let path = documentsDirectory.stringByAppendingPathComponent(fileName)
var dict = NSMutableDictionary()
var item0 = [1,2,3]
var item1 = [1,2,3,4]
var item2 = false
var item3 = "xInitializerItem_01"
dict.setObject([item0, item1, item2, item3], forKey: "selection_01")
item0 = [4,5,6]
item1 = [5,6,7,8]
item2 = true
item3 = "xInitializerItem_02"
dict.setObject([item0, item1, item2, item3], forKey: "selection_02")
dict.writeToFile(path, atomically: true)
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
println("Saved Data.plist file is --> \(resultDictionary?.description)")
}
That is may result from the code above:
You cannot append values to the plist, so everytime you save it you need to save all values again