iOS 8 Swift Read Plist

半腔热情 提交于 2019-12-06 08:08:16

问题


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.


回答1:


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 


来源:https://stackoverflow.com/questions/26391883/ios-8-swift-read-plist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!