Search code examples
iosswiftplist

iOS 8 Swift Read Plist


I want to read values from a plist file as integers. I have the following code:

let path = NSBundle.mainBundle().pathForResource("savedState", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)
let players: AnyObject = String(dict.valueForKey("players") as NSString)
let level: AnyObject = String(dict.valueForKey("level") as NSString)
let numPlayers = Int(players as NSNumber)
let playLevel = Int(level as NSNumber)

The let players: and let level: crash my app. I know this should be simple - I just can't figure out how to do it.


Solution

  • You may be looking for something like this:

    let path = NSBundle.mainBundle().pathForResource("savedState", ofType: "plist")
    let dict = NSDictionary(contentsOfFile: path!)
    let players = dict.valueForKey("players") as? String
    let level = dict.valueForKey("level") as? String
    let numPlayers = players != nil ? players!.toInt() : 0
    let playLevel = level != nil ? level!.toInt() : 0
    

    It attempts to read players and level from the plist as optional strings, then if they are non nil it sets numPlayers and playLevel to their Int value. If they are nil numPlayers and playLevel are set to 0. Although if your plist values are integers, why not just read them as Ints?

    let players = dict.valueForKey("players") as? Int
    let level = dict.valueForKey("level") as? Int