ios应用开发中plist的读写(Swift)

来源:互联网 发布:知乎精华化妆品 编辑:程序博客网 时间:2024/04/28 16:26

读取和存储数据是很多ios应用中常见的功能。有很多办法可以实现这个功能:NSUserDefaults、CoreData、使用plist等等。
今天要介绍的是如何使用plist来实现这个功能(使用swift语言)

下载资源

我们要使用一个GameData.plist文件,点击这里下载
打开它你将看到3个条目:
BedroomFloor(包括代码需要用到的具体floor的id)
BedroomWall(包括代码需要用到的具体wall的id)
XlnitializerItem(被代码使用 ,不要尝试去改变它)
这里写图片描述

创建你的项目

现在,让我们创建一个简单的项目。建立一个”Single View Application”
这里写图片描述

然后,将项目名设置为:ReadWritePlistTutorial并且选择Swift作为编程语言
这里写图片描述

设置你的项目
好,现在把GameData.plist文件拖进你的项目
这里写图片描述

要选择”Copy items if needed”并且目标地址选择”ReadWritePlistTutorial”
这里写图片描述

首先,我们要给plist Keys添加一些常量,添加在ViewController.swift文件中,在import UIKit之后
swift

// MARK: == GameData.plist  Keys ==let BedroomFloorKey = "BrdroomFloor"let BedroomWallKey = "BedroomWall"// MARK: -

现在,我们要添加两个辅助变量,添加在viewDidLoad()方法前
swift

//MARK: == Variables ==var bedroomFloorID: AnyObject = 101var bedroomWallID: AnyObject = 101

现在ViewController.swift文件应该是这样:
这里写图片描述

添加逻辑

我们想在代码中使用plist的元素,所以我们要把它读到代码中转换为字典。拷贝这段代码到didReceiveMemoryWarning()方法下面
swift

func loadGameData() {    // 获取GameData.plist的地址    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray    let documentsDirectory = paths[0]    let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")    let fileManager = NSFileManager.defaultManager()    //确认文件是否存在    if(!fileManager.fileExistsAtPath(path)) {    // 如果不存在,就从bundle中拷贝一份默认文件        if let bundlePath = NSBundle.mainBundle().pathForResource("GameData", ofType: "plist") {           let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)           print("Bundle GameData.plist file is --> \(resultDictionary?.description)")           do{               try fileManager.copyItemAtPath(bundlePath, toPath: path)           } catch{                    print("copy")}        } else {            print("GameData.plist not found. Please, make sure it is part of the bundle.")            }    } else {        print("GameData.plist already exits at path.")        // 使用这条命令删除目录中的文件        //fileManager.removeItemAtPath(path, error: nil)    }    let resultDictionary = NSMutableDictionary(contentsOfFile: path)    print("Loaded GameData.plist file is --> \(resultDictionary?.description)")    let myDict = NSDictionary(contentsOfFile: path)    if let dict = myDict {        //读取数值        bedroomFloorID = dict.objectForKey(BedroomFloorKey)!        bedroomWallID = dict.objectForKey(BedroomWallKey)!        //...    } else {        print("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!")    }}

然后添加这段代码来存储对plist的改动
swift

func saveGameData() {        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray        let documentsDirectory = paths.objectAtIndex(0) as! NSString        let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")        let dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]        //存储数值        dict.setObject(bedroomFloorID, forKey: BedroomFloorKey)        dict.setObject(bedroomWallID, forKey: BedroomWallKey)        //...        //写入GameData.plist        dict.writeToFile(path, atomically: false)        let resultDictionary = NSMutableDictionary(contentsOfFile: path)        print("Saved GameData.plist file is --> \(resultDictionary?.description)")    }

通常我们需要在程序启动时读取plist的数据,所以把读取plist的方法添加到viewDidLoad()中
这里写图片描述

添加按钮

要存储数据让我们现在故事版中创建一个按钮
这里写图片描述

重命名为“Save”并且按住Ctrl并拖动它到ViewController.swift来创建一个连接
这里写图片描述

选择Action连接并且输入名字:SaveButtonTapped
这里写图片描述

现在我们要把bedroomFloorID变为999并且保存到plist。
添加下面的代码到刚刚创建的IBAction里面:
swift

//改变bedroomFloorID的值bedroomFloorID = 999//保存修改到plistsaveGameData()

编译并运行

点击“Save”按钮,你将看到log中打印的变化记录
这里写图片描述

我们完成了。如果你关闭模拟器,并再次编译运行,会看到BedroomFloorID还是999.
另外,你可以把Save按钮设置在屏幕的正中间
提示:
这里写图片描述

2 0