iOS swift3.0 属性文件plist的应用

       前言:iOS的属性文件(Property List)是以.plist结尾,以文件形式存储信息。我通常会创建一个根字典rootDict,然后把需要的各种格式数据根据Key写进根字典保存起来,需要的时候再根据对应的Key把数据提出来。当然,文件只保存少量关键数据,APP退出也不会影响到的数据。

 

1. 文件路径-通常放在沙盒中的Documents文件夹中

//工程中(私有的沙箱目录)" Data.plist "文件的路径
let DataPlistPath: String! = Bundle.main.path(forResource: "Data", ofType: "plist")

//初始化localData.plist文件的路径;NSHomeDirectory:应用所存储的目录
let localPlistPath: String! = NSHomeDirectory() + "/Documents/localData.plist"

 

2. 初始化属性列表文件

func createEditableFileIfNeeded() {

       //根据localPlistPath判断localData.plist文件是否存在

       let fileManager = FileManager.default
       let dbexits = fileManager.fileExists(atPath: self.localPlistPath)        

       if !dbexits {
            //如果文件不存在则创建localData.plist文件
            fileManager.createFile(atPath: self.localPlistPath, contents: nil, attributes: nil)

            //初始化字典
            initData()
       }

}

3. 初始化数据

func initData() {

      //将字典类型的数据写入localData.plist

        let rootDict = NSMutableDictionary()
        //设置bool
        rootDict.setValue(true, forKey: "key_Bool")
        //设置array
        rootDict.setValue(["one","two"], forKey: "key_Array")
        //设置numberInt
        rootDict.setValue(1, forKey: "key_Int")
        //设置numberFloat
        rootDict.setValue(1.2, forKey: "key_Float")
        //设置dictionary
        rootDict.setValue(["key1":"value1","key2":"value2"], forKey: "key_Dictionary")
        //设置date
        rootDict.setValue(NSDate(), forKey: "key_Date")

        //将rootDict写入localData.plist文件
        rootDict.write(toFile: self.localPlistPath, atomically: true)

}

 

4. 读取localData.plist里的数据  

func readData(key:String) -> String? {

     let rootDict = NSMutableDictionary(contentsOfFile: self.localPlistPath)

     let data = rootDict?[key] as? String

     return data

}

 

5. 更新数据(修改读取到的rootDict,再把rootDict重新写入localData.plist)

func updateData(key:String, data:String) {

     let rootDict = NSMutableDictionary(contentsOfFile: self.localPlistPath)

     rootDict?.setValue(data, forKey: key)

     rootDict?.write(toFile: self.localPlistPath, atomically: true)

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值