i'm trying to understand how to save a simple value, an integer, in a plist. but i'm finding on the net only solution for save dictionary and array and i don't understand what i can change to work it only for an integer. this is the code for the moment...
var musicalChoice = 1
var musicString : String = "5"
override func viewDidLoad() {
super.viewDidLoad()
musicString = String(musicalChoice)}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func writePlist() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as NSString
let path = documentsDirectory.stringByAppendingPathComponent("Preferences.plist")
musicString.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error:nil )
}
func readPlist() {
}
You can't have anything other than an array or dictionary as the root object in a plist. This is because plist files are essentially special xml files so when you are trying to read the file you ask for object at key or object at index, otherwise you have no means of obtaining your data. Also, when inserting numbers into a plist, you must wrap them in the NSNumber class. To save your objects, check out this answer.
Update for Swift 4
I have created SwiftyPlistManager. Take a look at it on GiHub and follow these video instructions:
https://www.youtube.com/playlist?list=PL_csAAO9PQ8bKg79CX5PEfn886SMMDj3j
Update for Swift 3.1
Here's what I use to read/write a plist file in swift:
The plist file is this:
My variant function to read and write .plist on swift, tested on device.
Exapmle:
var dataVersion = readPlist("Options", key: "dataVersion")
writePlist("Options", key: "dataVersion", data: 1.23)
Function: