英文原文地址:http://www.swiftkiller.com/?p=559
或者:http://www.tuicool.com/articles/vY7vMjZ
项目代码:https://github.com/SandorNagy/ReadWritePlistTutorial
在许多iOS app中经常需要加载和保存数据。常见的有许多方法能完成这个功能:NSUserDefaults, CoreData,或者是用plist等等。今天这篇文章我将告诉大家怎么使用plist。
下载资源
我们将用到一个GameData.plist。点击下载
打开它你会看到以下三个内容
// MARK: == GameData.plist Keys ==
let BedroomFloorKey = "BedroomFloor"
let BedroomWallKey = "BedroomWall"
// MARK: -
// MARK: == Variables ==
var bedroomFloorID: AnyObject = 101
var bedroomWallID: AnyObject = 101
func loadGameData() {
// getting path to GameData.plist
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths[0] as String
let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")
let fileManager = NSFileManager.defaultManager()
//check if file exists
if(!fileManager.fileExistsAtPath(path)) {
// If it doesn't, copy it from the default file in the Bundle
if let bundlePath = NSBundle.mainBundle().pathForResource("GameData", ofType: "plist") {
let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
println("Bundle GameData.plist file is --> \(resultDictionary?.description)")
fileManager.copyItemAtPath(bundlePath, toPath: path, error: nil)
println("copy")
} else {
println("GameData.plist not found. Please, make sure it is part of the bundle.")
}
} else {
println("GameData.plist already exits at path.")
// use this to delete file from documents directory
//fileManager.removeItemAtPath(path, error: nil)
}
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
println("Loaded GameData.plist file is --> \(resultDictionary?.description)")
var myDict = NSDictionary(contentsOfFile: path)
if let dict = myDict {
//loading values
bedroomFloorID = dict.objectForKey(BedroomFloorKey)!
bedroomWallID = dict.objectForKey(BedroomWallKey)!
//...
} else {
println("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!")
}
}
接下来添加下面的代码用来把值保存到plist文件中。
func saveGameData() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as NSString
let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")
var dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]
//saving values
dict.setObject(bedroomFloorID, forKey: BedroomFloorKey)
dict.setObject(bedroomWallID, forKey: BedroomWallKey)
//...
//writing to GameData.plist
dict.writeToFile(path, atomically: false)
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
println("Saved GameData.plist file is --> \(resultDictionary?.description)")
}
就这样,我们运行一下来看编译的一切。
//change bedroomFloorID variable value
bedroomFloorID = 999
//save the plist with the changes
saveGameData()
然后编译运行,点击Save按钮,看到在Log中的变化.