iOS開發(fā) Plist 文件實(shí)現(xiàn)增、刪、查、改

①有時(shí)候進(jìn)行少量數(shù)據(jù)持久化存儲(chǔ)時(shí)候,可使用屬性列表 Plist 文件。
②如項(xiàng)目中要使用比較多的配置數(shù)據(jù),可生成 Plist 后再轉(zhuǎn)移到項(xiàng)目中

下面例子簡(jiǎn)單實(shí)現(xiàn)對(duì)于在沙盤下的 Plist 文件進(jìn)行增刪查改操作。

保存
更改
刪除
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文件,不存在則創(chuàng)建
    func createPlistFile() {
        //獲取路徑
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
        filePath = path.stringByAppendingString("/data666.plist")
        //###注意加橫桿“/”,否則真機(jī)測(cè)試崩潰,因?yàn)闊o法寫入####
        
        if !NSFileManager.defaultManager().fileExistsAtPath(filePath) {
            let rootDic = NSMutableDictionary()
            rootDic.writeToFile(filePath, atomically: true)
        }
    }
    
    //遍歷數(shù)據(jù)
    func findPlistFileData() -> Bool {
        
        if let dicData = NSMutableDictionary(contentsOfFile: filePath) {
            for (k,_) in dicData {
                // 判斷是否存在相同的學(xué)號(hào)
                if userNumber.text! == (k as! String) {
                    return true
                }
            }
        }
        return false
    }
    
    //保存數(shù)據(jù)
    func savePlistData() {
        
        let rootDic = NSMutableDictionary(contentsOfFile: filePath) //根
        let userDataDic = NSMutableDictionary()  //二級(jí)
        userDataDic.setObject(userAge.text!, forKey: "age")
        userDataDic.setObject(userName.text!, forKey: "name")
        rootDic!.setObject(userDataDic, forKey: userNumber.text!)
        rootDic!.writeToFile(filePath, atomically: true)
        print("保存成功")
    }
    
    //刪除數(shù)據(jù)
    func deletePlistData() {

        let rootDic = NSMutableDictionary(contentsOfFile: filePath) //根
        rootDic!.removeObjectForKey(userNumber.text!) //二級(jí)
        rootDic!.writeToFile(filePath, atomically: true)
        print("刪除成功")
    }
    
    // MARK: - Action
    // 保存按鈕
    @IBAction func saveData(sender: UIButton) {
        //門衛(wèi) 檢查
        guard findPlistFileData() == false else {
            let alert = UIAlertController(title: "學(xué)號(hào)已存在", message: "是否要覆蓋當(dāng)前學(xué)號(hào)所有內(nèi)容", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "是的", style: .Default, handler: { (action) -> Void in
                
                self.savePlistData() //保存數(shù)據(jù)
            }))
            alert.addAction(UIAlertAction(title: "否", style: .Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
            return
        }
        
        self.savePlistData() //保存數(shù)據(jù)
        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) {
        //門衛(wèi) 檢查
        guard findPlistFileData() == true else {
            let alert = UIAlertController(title: "學(xué)號(hào)不存在", message: "請(qǐng)查看是否輸入有誤", 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() //刪除數(shù)據(jù)
    }
    
    // 查找按鈕
    @IBAction func findData(sender: UIButton) {
        guard findPlistFileData() == true else {
            print("該學(xué)號(hào)不存在")
            return
        }
        if let dicData = NSMutableDictionary(contentsOfFile: filePath) {
            for (k,v) in dicData {
                if userNumber.text! == (k as! String) {
                    let dic2 = v as! NSDictionary
                    print("該學(xué)號(hào)已存在")
                    for (k1, v2) in dic2 {
                        print("\(k1): \(v2)")
                    }
                }
            }
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,932評(píng)論 25 709
  • "蝦虎魚一定會(huì)待在槍蝦身邊。"笹垣把他們比喻成這樣互利共生的存在。 雪穗對(duì)夏美說:"我的天空里沒有太陽...
    陳斯墨閱讀 1,473評(píng)論 1 1
  • 2017,搞事情?2017,搞點(diǎn)事情。 一 文藝點(diǎn)講,總有一顆追求藝術(shù)的心,卻力不從心。 其實(shí)就是看著UI設(shè)計(jì)師的...
    小編閱讀 580評(píng)論 0 0
  • "目錄號(hào): HY-13945 Others- NVP-231是高效可逆的CerK抑制劑,IC50為12 nM,能競(jìng)...
    莫小楓閱讀 254評(píng)論 0 0
  • 三、關(guān)于藏頭詩與嵌名詩的創(chuàng)作 作為一名詩詞愛好者和創(chuàng)作者,應(yīng)該時(shí)時(shí)刻刻謹(jǐn)記:古詩詞本來就是戴著鐐銬跳舞的一種思想行...
    xueshuai閱讀 2,110評(píng)論 7 4

友情鏈接更多精彩內(nèi)容