iOS开发 Plist 文件实现增、删、查、改

①有时候进行少量数据持久化存储时候,可使用属性列表 Plist 文件。
②如项目中要使用比较多的配置数据,可生成 Plist 后再转移到项目中

下面例子简单实现对于在沙盘下的 Plist 文件进行增删查改操作。

保存
更改
删除
import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var userNumber: UITextField!
    @IBOutlet weak var userName: UITextField!
    @IBOutlet weak var userAge: UITextField!
    
    var filePath = "" //文件路径
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.createPlistFile()
    }
    
    //判断是否存在该plist文件,不存在则创建
    func createPlistFile() {
        //获取路径
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
        filePath = path.stringByAppendingString("/data666.plist")
        //###注意加横杆“/”,否则真机测试崩溃,因为无法写入####
        
        if !NSFileManager.defaultManager().fileExistsAtPath(filePath) {
            let rootDic = NSMutableDictionary()
            rootDic.writeToFile(filePath, atomically: true)
        }
    }
    
    //遍历数据
    func findPlistFileData() -> Bool {
        
        if let dicData = NSMutableDictionary(contentsOfFile: filePath) {
            for (k,_) in dicData {
                // 判断是否存在相同的学号
                if userNumber.text! == (k as! String) {
                    return true
                }
            }
        }
        return false
    }
    
    //保存数据
    func savePlistData() {
        
        let rootDic = NSMutableDictionary(contentsOfFile: filePath) //根
        let userDataDic = NSMutableDictionary()  //二级
        userDataDic.setObject(userAge.text!, forKey: "age")
        userDataDic.setObject(userName.text!, forKey: "name")
        rootDic!.setObject(userDataDic, forKey: userNumber.text!)
        rootDic!.writeToFile(filePath, atomically: true)
        print("保存成功")
    }
    
    //删除数据
    func deletePlistData() {

        let rootDic = NSMutableDictionary(contentsOfFile: filePath) //根
        rootDic!.removeObjectForKey(userNumber.text!) //二级
        rootDic!.writeToFile(filePath, atomically: true)
        print("删除成功")
    }
    
    // MARK: - Action
    // 保存按钮
    @IBAction func saveData(sender: UIButton) {
        //门卫 检查
        guard findPlistFileData() == false else {
            let alert = UIAlertController(title: "学号已存在", message: "是否要覆盖当前学号所有内容", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "是的", style: .Default, handler: { (action) -> Void in
                
                self.savePlistData() //保存数据
            }))
            alert.addAction(UIAlertAction(title: "否", style: .Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
            return
        }
        
        self.savePlistData() //保存数据
        let alert = UIAlertController(title: "保存成功", message: "", preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
    
    
    // 删除按钮
    @IBAction func deleteData(sender: UIButton) {
        //门卫 检查
        guard findPlistFileData() == true else {
            let alert = UIAlertController(title: "学号不存在", message: "请查看是否输入有误", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "确定", style: .Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
            return
        }
        let alert = UIAlertController(title: "删除成功", message: "", preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "确定", style: .Cancel, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
        self.deletePlistData() //删除数据
    }
    
    // 查找按钮
    @IBAction func findData(sender: UIButton) {
        guard findPlistFileData() == true else {
            print("该学号不存在")
            return
        }
        if let dicData = NSMutableDictionary(contentsOfFile: filePath) {
            for (k,v) in dicData {
                if userNumber.text! == (k as! String) {
                    let dic2 = v as! NSDictionary
                    print("该学号已存在")
                    for (k1, v2) in dic2 {
                        print("\(k1): \(v2)")
                    }
                }
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,142评论 25 709
  • "虾虎鱼一定会待在枪虾身边。"笹垣把他们比喻成这样互利共生的存在。 雪穗对夏美说:"我的天空里没有太阳...
    陈斯墨阅读 5,136评论 1 1
  • 2017,搞事情?2017,搞点事情。 一 文艺点讲,总有一颗追求艺术的心,却力不从心。 其实就是看着UI设计师的...
    小编阅读 3,465评论 0 0
  • "目录号: HY-13945 Others- NVP-231是高效可逆的CerK抑制剂,IC50为12 nM,能竞...
    莫小枫阅读 1,553评论 0 0
  • 三、关于藏头诗与嵌名诗的创作 作为一名诗词爱好者和创作者,应该时时刻刻谨记:古诗词本来就是戴着镣铐跳舞的一种思想行...
    xueshuai阅读 5,912评论 7 4