精华内容
下载资源
问答
  • Swift 读写 plist 文件

    千次阅读 2018-07-26 22:10:08
    在MacOS项目中使用Swift管理plist,实现读写plist文件。 1. Jobs.swift 使用Jobs类管理Jobs.plist // Jobs.swift // Created by Cyril on 18/7/11. // Copyright © 2018年 GJ. All rights reserved. import ...

    在MacOS项目中使用Swift管理plist,实现读写plist文件。

    1. Jobs.swift
    使用Jobs类管理Jobs.plist

    //  Jobs.swift
    //  Created by Cyril on 18/7/11.
    //  Copyright © 2018年 GJ. All rights reserved.
    import Foundation
    class Jobs: NSObject {
        var RestoreSequence_1: Dictionary<String , AnyObject?> = [:]
        var RestoreSequence_2: Dictionary<String , AnyObject?> = [:]
        var RestoreSequence_3: Dictionary<String , AnyObject?> = [:]
        let dModel = DataModel()
        //构造方法
        override init(){
            super.init()
            print("[Jobs] 初始化...")
            onCreateData("Jobs.plist")
            let d = dModel.loadData("Jobs", dFilePath: "Jobs.plist")
            let skey:String = "RestoreStage"
            print("查找\(skey)结果:\(dModel.searchValueByKey(d, skey: skey))")
        }
        func onCreateData(fileName: String){
            print("[Jobs]: 开始创建plist文件")
            //Document path   本地数据数据路径   .plist格式
            let fileManager = NSFileManager.defaultManager()
            let localDataPath:String = dModel.dataFilePath(fileName)
            print("[Jobs]: " + localDataPath)
            var isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
            print("isLocalDataExisted->\(isLocalDataExisted)")
    
            //判断.plist文件是否存在
            if isLocalDataExisted == false//文件不存在
            {
                fileManager.createFileAtPath(localDataPath, contents: nil, attributes: nil)//创建.plist文件
            }
            isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
            print("isLocalDataExisted->\(isLocalDataExisted)")
    
            //设置root
            let root = NSMutableDictionary()
            //设置dictionay
            root.setValue(
                [
                    "RestoreSequence_1":[
                        "RestoreStage" : "P1",
                        "Input_Type" : "Uart_Diags",
                        "TempValues" : [
                            "MLBSN" : "#ProgramWriteToIt#",
                            "FGSN" : "#ProgramWriteToIt#",
                            "Mod#" : "#ProgramWriteToIt#",
                            "Regn" : "#ProgramWriteToIt#",
                        ],
                        "Command_Device" : [
                            "TTPowerSupply" : "#TT治具上电命令#",
                            "MLBSN" : "syscfg print MLB#",
                            "Write_FGSN" : "sn #FGSN#",
                            "Print_FGSN" : "sn",
                            "Write_Mod" : "syscfg add Mod# #Mod##",
                            "Print_Mod" : "syscfg print Mod#",
                            "Write_Regn" : "syscfg add Regn #Regn#",
                            "Print_Regn" : "syscfg print Regn",
                            "LogCollection" : "#LogCollection#",
                            "Restart" : "#TT治具重新上电命令#"
                        ],
                        "Command_Host" : [
                            "暂时为空" : "暂时为空"
                        ]
                    ],
                    "RestoreSequence_2":[
                        "RestoreStage" : "P2",
                        "Input_Type" : "Uart_iBoot",
                        "TempValues" : [
                            "MLBSN" : "#ProgramWriteToIt#",
                            "FGSN" : "#ProgramWriteToIt#",
                            "#暂时为空#" : "#暂时为空#",
                        ],
                        "Command_Device" : "#暂时为空#",
                        "Command_Host" : [
                            "暂时为空" : "暂时为空"
                        ]
                    ],
                    "RestoreSequence_FG":[
                        "RestoreStage" : "FG",
                        "Input_Type" : "Uart_OS",
                        "TempValues" : [
                            "FGSN" : "#ProgramWriteToIt#",
                            "#暂时为空#" : "#暂时为空#",
                        ],
                        "Command_Device" : "#暂时为空#",
                        "Command_Host" : [
                            "暂时为空" : "暂时为空"
                        ]
                    ],
    
                ], forKey: "Jobs")
            //将root写入.plist文件
            root.writeToFile(localDataPath, atomically: true)
            isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
            if isLocalDataExisted == true{
                print("[Jobs]: Jobs.plist文件创建完成")
            }else{
                print("[Jobs]: Jobs.plist文件创建失败")
            }
            /*  try! fileManager.removeItemAtPath(localDataPath)//删除本地数据文件 */
        }    
    }
    

    2. DataModel.swift

    //  DataModel.swift
    //  Created by Cyril on 18/7/11.
    //  Copyright © 2018年 GJ. All rights reserved.
    
    import Foundation
    class DataModel: NSObject {
        var userList = [UserInfo]()
       // var keyArray: Dictionary = [Int: String] ()
        //获取沙盒文件夹路径
        func documentsDirectory()->String {
            /*  let paths = NSSearchPathForDirectoriesInDomains(
             NSSearchPathDirectory.DocumentationDirectory,NSSearchPathDomainMask.UserDomainMask,true)
             let documentsDirectory:String = paths.first! as String */
            let path = "./Cyril/Anole"
            return path
        }
    
        /**
         获取数据文件地址
         Eg:
         fileName:userList.plist
         */
        func dataFilePath (fileName: String)->String{
            print(documentsDirectory().stringByAppendingString("/" + fileName))
            return documentsDirectory().stringByAppendingString( "/\(fileName)")
        }
    
        /**
         读取数据
         Eg:
         key: userList
         dFilePath: userList.plist
         */
        func loadData(key: String, dFilePath: String)-> NSDictionary{
            //判断.plist文件是否存在
            let fileManager = NSFileManager.defaultManager()
            let isLocalDataExisted = fileManager.fileExistsAtPath(self.dataFilePath(dFilePath))
            print("isLocalDataExisted->\(isLocalDataExisted)")
            if isLocalDataExisted == false//文件不存在
            {
                fileManager.createFileAtPath(self.dataFilePath(dFilePath), contents: nil, attributes: nil)//创建.plist文件
            }
            let dicFromPList: NSDictionary? = NSDictionary(contentsOfFile: "/Users/coreos/Desktop/Cyril/Anole/Jobs_P1P2FG.plist")
            print("文件 " + dFilePath + " 读取完成")
            return dicFromPList!
        }
    
        /**
         * 通过key查找在字典中的value值
         */
        func searchValueByKey(dic: NSDictionary, skey: String)-> String{
            var printHead = "[searchValueByKey]: "
            if (dic.count == 0){
                return printHead + "输入的参数字典为空"
            }
            //plist 四层结构遍历(尚有bug未更正)
            for (key1, value1) in (dic as! NSMutableDictionary) {
          //      keyArray.updateValue(key as! String, forKey: 1)
                print("第1层->字典 key \(key1) -  字典 value () \(value1)")
                if(key1 as! String == skey){
                    print("\(printHead)\(skey)查找成功, 为根字典")
                    return "查找的\(skey)的值为\(value1)"
                }
                for (key2, value2) in (value1 as! NSMutableDictionary) {
                    print("第2层->字典 key \(key2) -  字典 value \(value2)")
                    if(key2 as! String == skey){
                        print("\(printHead)\(skey)查找成功, 在字典\(key1)下")
                        return "查找的\(skey)的值为\(value2)"
                    }
                    for (key3, value3) in (value2 as! NSMutableDictionary) {
    
                        print("第3层->字典 key \(key3) -  字典 value \(value3)")
                        if(key3 as! String == skey){
                            print("\(printHead)\(skey)查找成功, 在字典\(key2)下")
                            return "查找的\(skey)的值为\(value3)"
                            for (key4, value4) in (value3 as! NSMutableDictionary) {
    
                                print("第4层->字典 key \(key4) -  字典 value \(value4)")
                                if(key4 as! String == skey){
                                    print("\(printHead)\(skey)查找成功, 在字典\(key3)下")
                                    return "查找的\(skey)的值为\(value4)"
                                }
                            }
                        }
                    }
                }
            }
            return "\(printHead)输入的参数字典为空"
        }
    
        /**
         *  值类型判断
         */
        func judgeValueType(dic: AnyObject) -> String{
            if let dict1 = dic as? NSMutableDictionary{
                return "NSMutableDictionary"
            }else if let dict1 = dic as? NSDictionary{
                return "NSDictionary"
            }else if let dict1 = dic as? NSArray{
                return "NSArray"
            }else if  let dict1 = dic as? NSValue{
                return "NSValue"
            }else{
                return "\(dic)" //其他可能是字串类型
            }
        }
    }
    展开全文
  • swift获取plist文件

    千次阅读 2018-12-20 13:59:09
    VC里面获取文件路径搭建界面 import UIKit class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{ var tbv:UITableView? var nameArr:[String] = [] var dict:NSDictionary =...

    VC里面获取文件路径搭建界面

    import UIKit
    
    class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
    
        var tbv:UITableView?
        var nameArr:[String] = []
        
        var dict:NSDictionary = [:]
        var data:NSMutableDictionary = [:]
        
        var marr:NSMutableArray = []
        
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            
            // 生成文件的存储路径
            let plistPath = Bundle.main.path(forResource: "plist", ofType: "plist")
           // let plistPath = Bundle.main.path(forResource: "1", ofType: "plist")
            
            //读取属性列表文件,并转化为可变字典对象
            data = NSMutableDictionary(contentsOfFile: plistPath!)!
        
           // marr = NSMutableArray(contentsOfFile: plistPath!)!
           // print(marr)
            nameArr = data.allKeys as! [String]
            
            tbv = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
            view.addSubview(tbv!)
            
            tbv?.delegate = self
            tbv?.dataSource = self
            
            tbv?.register(UITableViewCell.self, forCellReuseIdentifier: "idCell")
            
        }
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          //  return marr.count
            return nameArr.count
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
            let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "idCell")!
            cell.textLabel?.text = nameArr[indexPath.row];
    //        let dic:NSDictionary = marr[indexPath.row] as! NSDictionary
    //        let arr:NSArray = dic.allKeys as NSArray
    //        cell.textLabel?.text = arr[0] as? String;
            return cell
        }
        
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            
            if nameArr[indexPath.row]=="国外"{
                dict = data["国外"] as! NSDictionary
                let vc:SecondVC = SecondVC()
                
                vc.dict = dict
                
                self.navigationController?.pushViewController(vc, animated: true)
                
            }else{
                
                dict = data["国内"] as! NSDictionary
                
                let vc:ThreeVC = ThreeVC()
                
                vc.dict = dict
                
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
    

    跳第二个界面

    import UIKit
    
    class SecondVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
        var dict:NSDictionary = [:]
        var tbv:UITableView?
        
        var nameArr:[String] = []
        
        
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view.
            
            view.backgroundColor = UIColor.white
            
            nameArr = dict.allKeys as! [String];
            
            tbv = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
            view.addSubview(tbv!)
            
            tbv?.delegate = self
            tbv?.dataSource = self
            
            tbv?.register(UITableViewCell.self, forCellReuseIdentifier: "idCell")
            
        }
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return nameArr.count
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
            let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "idCell")!
            cell.textLabel?.text = nameArr[indexPath.row];
            return cell
        }
        
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            
            if nameArr[indexPath.row]=="Britney Spears"{
                
                let arr:NSArray = dict["Britney Spears"] as! NSArray
                
                let vc:FourVC = FourVC()
                
                vc.dict = arr
                
                self.navigationController?.pushViewController(vc, animated: true)
                
            }else{
                let arr:NSArray = dict["Kelly Clarkson"] as! NSArray
                let vc:FourVC = FourVC()
                
                vc.dict = arr
                
                self.navigationController?.pushViewController(vc, animated: true)
            }
            
        }
    
    }
    

    再跳到播放界面记得导入框架AVFoundation

    import UIKit
    import AVFoundation
    
    class FourVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
        
        var dict:NSArray = []
        var tbv:UITableView?
        var audioPlayer: AVAudioPlayer?
      //  var nameArr:[String] = []
        var select:Bool = true
        
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view.
            
            // 设置音乐
            let path = Bundle.main.path(forResource: "试音碟-高山流水 (古筝)", ofType: "mp3")
            let pathURL=NSURL(fileURLWithPath: path!)
            do {
                audioPlayer = try AVAudioPlayer(contentsOf: pathURL as URL)
            } catch {
                audioPlayer = nil
            }
            
            audioPlayer?.prepareToPlay()
            
            view.backgroundColor = UIColor.white
            
            tbv = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
            view.addSubview(tbv!)
            
            tbv?.delegate = self
            tbv?.dataSource = self
            
            tbv?.register(UITableViewCell.self, forCellReuseIdentifier: "idCell")
        }
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return dict.count
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
            let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "idCell")!
            cell.textLabel?.text = (dict[indexPath.row] as! String);
            return cell
        }
        
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            
            if select==true {
                audioPlayer?.play()
                select = false
            }else{
                audioPlayer?.pause()
                select = true
            }
            
           // let audioPlayer = MusicViewController()
          //  audioPlayer.playMusic(filePath)
          //  self.navigationController!.pushViewController(audioPlayer, animated: true)
        }
    }
    
    
    展开全文
  • Swift plist文件读写

    千次阅读 2015-01-05 17:01:11
    //写入plist var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) //Get Path of Documents Directory var ...
    <pre name="code" class="plain">
    1. //写入plist
    2. var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) //Get Path of Documents Directory
    3. var documentsDirectory:AnyObject = paths[0]
    4. var path = documentsDirectory.stringByAppendingPathComponent("samplePlist.plist")
    5. var fileManager = NSFileManager.defaultManager()
    6. var fileExists:Bool = fileManager.fileExistsAtPath(path)
    7. var data : NSMutableDictionary?
    8. //Check if plist file exists at path specified
    9. if fileExists == false {
    10. //File does not exists
    11. data = NSMutableDictionary () //Create data dictionary for storing in plist
    12. } else {
    13. //File exists – retrieve data from plist inside data dictionary
    14. data = NSMutableDictionary(contentsOfFile: path)
    15. }
    16. data?.setValue("\(countButton)", forKey: "NumeroButton")
    17. data?.writeToFile(path, atomically: true) //Write data to file permanently
    
    
    //读plist
     
    
    <ol class="linenums" style="margin: 0px 0px 0px 3em; padding: 0px; border: 0px; outline: 0px; font-size: 13px; font-family: monospace; vertical-align: baseline; list-style: none; color: rgb(62, 62, 62); line-height: 22px; white-space: pre; background-color: rgb(250, 250, 250);"><li class="L0" style="margin: 5px 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; list-style: decimal !important;"><span class="com" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(136, 0, 0);">//Get path of Documents directory</span></li><li class="L1" style="margin: 5px 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; background-color: rgb(240, 240, 240); list-style: decimal !important;"><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);">    </span><span class="kwd" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 221);">var</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);"> paths </span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">=</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);"> </span><span class="typ" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 0, 102);">NSSearchPathForDirectoriesInDomains</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">(</span><span class="typ" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 0, 102);">NSSearchPathDirectory</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">.</span><span class="typ" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 0, 102);">DocumentDirectory</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">,</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);"> </span><span class="typ" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 0, 102);">NSSearchPathDomainMask</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">.</span><span class="typ" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 0, 102);">UserDomainMask</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">,</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);"> </span><span class="kwd" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 221);">true</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">)</span></li><li class="L2" style="margin: 5px 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; list-style: decimal !important;"><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);">    </span><span class="kwd" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 221);">var</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);"> documentsDirectory</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">:</span><span class="typ" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 0, 102);">AnyObject</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);"> </span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">=</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);"> paths</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">[</span><span class="lit" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 102, 102);">0</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">]</span></li><li class="L3" style="margin: 5px 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; background-color: rgb(240, 240, 240); list-style: decimal !important;"><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);">     </span><span class="kwd" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 221);">var</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);"> path </span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">=</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);"> documentsDirectory</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">.</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);">stringByAppendingPathComponent</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">(</span><span class="str" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 136, 0);">"samplePlist.plist"</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">)</span></li><li class="L4" style="margin: 5px 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; list-style: decimal !important;"><span class="com" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(136, 0, 0);">//Retrieve contents from file at specified path</span></li><li class="L5" style="margin: 5px 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; background-color: rgb(240, 240, 240); list-style: decimal !important;"><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);">    </span><span class="kwd" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 221);">var</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);"> data </span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">=</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);"> </span><span class="typ" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 0, 102);">NSMutableDictionary</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">(</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);">contentsOfFile</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">:</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);"> path</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">!)</span></li><li class="L6" style="margin: 5px 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; list-style: decimal !important;"><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);">   println</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">(</span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(0, 0, 0);">path</span><span class="pun" style="margin: 0px; padding: 0px; border: 0px; outline: 0px; font-style: inherit; font-family: inherit; vertical-align: baseline; color: rgb(102, 102, 0);">)</span></li></ol>
    
    
    
    原文地址:http://iphonedevsdk.com/forum/iphone-sdk-development/120452-swift-save-reload-data-to-plist.html
    展开全文
  • Swift读写plist文件教程及代码

    千次阅读 2015-09-09 19:36:49
    英文原文地址:http://www.swiftkiller.com/?p=559...在许多iOS app中经常需要加载和保存数据。常见的有许多方法能完成这个功能:NSUserDefaults, CoreData,或者是用plist等等。今天这篇文章我将告诉大家怎么使用plist

    英文原文地址: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。点击下载

    打开它你会看到以下三个内容

    • BedroomFloor (代码中将要用到的带有ID的特定floor)
    • BedroomWall (代码中将要用到的带有ID的特定wall)
    • XInitializerItem (代码中将要用到的,不能被改变的)
    创建工程
    创建一个简单的工程,选择Single View Application.

    然后起一个名字:ReadWritePlistTutorial,确保语言选择Swift

    设置工程
    好的,现在我们把刚才下载的GameData.plist拖到你的工程里。

    确保选择了Copy items if needed并且目标是ReadWritePlistTutorial.

    首先我们要为这个plist的关键字添加一些常量。添加下面代码到ViewController.swift里的import UIKit之后。
    // MARK: == GameData.plist Keys ==
      let BedroomFloorKey = "BedroomFloor"
      let BedroomWallKey = "BedroomWall"
      // MARK: -
    现在继续添加两个辅助变量在viewDidLoad方法前边。
    // MARK: == Variables ==
      var bedroomFloorID: AnyObject = 101
      var bedroomWallID: AnyObject = 101
    现在你的ViewController应该是这样

    添加逻辑
    我们想要能够在代码中使用plist文件元素,所以我们要把它转换成字典类型加载到我们的代码里。复制下面的代码在didReceiveMemoryWarning()方法之后。
    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)")
    }
        就这样,我们运行一下来看编译的一切。
    通常我们需要在app一开始运行时候就获取到plist中的数据,为此我们在viewDidLoad()中调用plist.

    为了保存一些数据我们首先在Main.storyboard中创建一个button.


    把它重命名,然后按住Ctrl键,点击按钮拖到ViewController.swift中以建立一个连接。


    选择Action连接,命名为:SaveButtonTapped.

    现在假设你想改变bedroomFloorID为999并且保存在plist中,添加以下代码到 saveButtonTapped IBAction.
    //change bedroomFloorID variable value
      bedroomFloorID = 999
      //save the plist with the changes
      saveGameData()
        然后编译运行,点击Save按钮,看到在Log中的变化.


    完成之后,如果你关闭app然后再次编译运行,BedroomFloorID 将会变为999
    注:你可能想把Save按钮的位置在app屏幕上居中,然而那是另一个教程提示一下:



    展开全文
  • plist内容如图 viewController.swift class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var cells : NSDictionary? // Global Variable override fu
  • swift 读取info.plist文件中的信息

    千次阅读 2018-10-24 12:59:30
    //在顶部状态栏显示风火轮(iPhonex之后没有好像)  UIApplication.shared.isNetworkActivityIndicatorVisible = true ...// 读取info.plist中的信息  let mainBundle = Bundle.main  let identifer = mainB...
  • Swift中数组字典和plist文件的转换 注意: Swfit中的Array和Dictionary是结构体,是值类型, 没有与plist相关的接口, 需要先转换为对应的Objectivc-C类型 1. Array转为plist文件(Dictionary类型同理) // 可能会使用到...
  • 1、新建 ...let unit_path = Bundle.main.path(forResource: "文件名(xxx)", ofType: "plist(文件类型)") //获取此文件所在的路径 let unit_data:NSMutableDictionary = NSMutableDictionary.i...
  • swift plist写入和读取数据

    千次阅读 2018-08-23 19:54:38
    //向指定的plist中写入数据--fileName: text.plist class ZQPredictProductIdSaveManager: NSObject { //写入 class func saveData(key: String, value: Any, fileName: String) -&gt; () { le...
  • 关于plist文件存储方式(swift

    千次阅读 2017-06-28 11:09:56
    这种存储方式非常常用,它操作方便,这是系统给的一个单例类,直接操作沙盒中的Library中的Preferences中的一个名为本应用的BundleID的plist文件。但是它只适合存储用户的一些偏好设置,不易存储大量数据,它在软件...
  • 实现plist文件 首先得先创建plist文件 在这里插入图片描述 创建方法 然后根据我们给出的题干设计plist文件 plist文件 之后我们需要把这个plist传到表格上,我采用的是直接放在表格上数据,如果有大神可以教教我...
  • swift-----读取 plist文件

    2015-05-29 10:01:00
    plist文件内容   "1.0" encoding= "UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" " http://www.apple.com/DTDs/PropertyList-1.0.dtd " > <plist version= "1.0">       ...
  • IOS学习 --- Swift 对于plist文件读写

    千次阅读 2015-05-08 15:18:36
    //System Medicine Name var plistPath = NSBundle.mainBundle().pathForResource("Medicine", ofType: "plist") var array = NSArray(contentsOfFile: plistPath!)! var custo
  • Swift - .plist文件数据的读取和存储

    千次阅读 2016-08-11 16:00:54
    Swift - .plist文件数据的读取和存储 2015-09-28 09:37发布:hangge 每次在Xcode中新建一个iOS项目后,都会自己产生一个.plist文件,里面记录项目的一些配置信息。我们也可以自己创建.plist文件来进行...
  • ios swift plist文件

    2018-11-22 11:07:53
    //读取属性列表文件,并转化为可变字典对象 data = NSMutableDictionary(contentsOfFile: plistPath!)! nameArr = data.allKeys as! [String] tbv = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen...
  • 读取plist文件

    2015-10-08 13:01:17
    //取得mainBundle NSBundle *bundle ... //取得文件路径  NSString *plistPath = [bundle pathForResource:@"文件名" ofType:@"plist"]; // 或可以写成 NSString *plistPath = [[NSBundle mainBundle]
  • swift plist文件

    2015-09-14 22:38:57
    1.创建pliet文件 new file->Resource->Property List 输入plist文件名称   2.Root 和Item的设置 3.  var CellInfor : NSMutableArray! let bundle = NSBundle.mainBundle() // 创建bundle
  • //plist文件,即属性列表文件,是一种用来存储串行化后的对象的文件。 import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional ...
  • 参考原文:...属性列表文件的扩展名为.plist ,因此通常被称为plist文件。文件是xml格式的。Plist文件通常用于储存用户设置,也可以用于存储捆绑的信息二.文件保存到的几个位置1. 工...
  • 前言 直接将数据写在代码里面,不是一种合理的做法。如果数据经常改,就要经常翻开...一般可以使用属性列表文件存储 NSArray 或者 NSDictionary 之类的数据,这种 “属性列表文件” 的扩展名是 plist,因此也称为...
  • let APP_NAME = Bundle.main.infoDictionary!["CFBundleName"] as! String let APP_VERSION = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String let kAgient = APP_NAME+APP_VERSION
  • 转自:http://blog.csdn.net/hard_working1/article/details/50756983下面通过一个...1,点击“保存”将联系人存入userList.plist文件中 2,点击“读取”从数据文件中加载解析出联系人注意: 1,本例使用了NSCoder,
  • iOS开发中怎么创建Plist文件

    千次阅读 2018-05-25 17:02:25
    1.就是手动创建.plist文件。 选中Xcode,使用快捷方式command+N 创建plist文件1.png 创建plist文件2.png 手动添加属性.png 注意:只能读取,不能用代码进行更删改查。。(如果本身plist文件在bundle...
  • 前言:iOS的属性文件(Property List)是以.plist结尾,以文件形式存储信息。我通常会创建一个根字典rootDict,然后把需要的各种格式数据根据Key写进根字典保存起来,需要的时候再根据对应的Key把数据提出来。当然,...
  • pist 最为持久化保存的一种方式!本身plist文件是xml ,对于小数量数据可以采用plis 的方法!这样更高效!

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,361
精华内容 544
关键字:

swift读取plist文件