【问题标题】:Swift 2 iOS 9: Plist Reading and WritingSwift 2 iOS 9:Plist 读写
【发布时间】:2015-07-28 23:20:36
【问题描述】:

我相信 Swift 2 中发生了一些变化,因为似乎没有关于如何读取和写入属性列表的教程有效。

任何开发 iOS 9 的人都可以分享他们在 Xcode 7 上使用 Swift 2 对 Plist 进行 R/W 的方法吗?

【问题讨论】:

  • 你能把你试过的代码和它给出的错误贴出来吗?

标签: plist swift2 xcode7 ios9


【解决方案1】:

这适用于 iOS 9 和 Xcode 7:

let filePath = NSBundle.mainBundle().pathForResource("FileName", ofType: "plist")!    
let stylesheet = NSDictionary(contentsOfFile:filePath)

唯一的问题是结果是NSDictionary 而不是Dictionary

【讨论】:

    【解决方案2】:

    希望这会有所帮助 - 没有代码很难回答。

    让我感到困惑的变化是,当将 plist 文件复制到文档目录时,方法 stringByAppendingPathComponent 不再可用。您必须改用 NSURL。

    如果您有一个 preparePlistForUseMethod,它现在应该如下所示。

    let rootPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true)[0]
            let url = NSURL(string: rootPath)
            plistPathInDocument = (url?.URLByAppendingPathComponent("plistfilename.plst").absoluteString)!
    
    if !NSFileManager.defaultManager().fileExistsAtPath(plistPathInDocument){
                let plistPathInBundle = NSBundle.mainBundle().pathForResource("plistfilename.plst", ofType: "plist")!
    
                do{
                try NSFileManager.defaultManager().copyItemAtPath(plistPathInBundle, toPath: plistPathInDocument)
                    print("plist copied")
                }
                catch{
                    print("error copying plist!")
                }
            }
            else{
                print("plst exists \(plistPathInDocument)")
        }
    }
    

    【讨论】:

    • 我注意到一个问题,我以 NSDicrionary 的身份访问,而结构是数组形式,并且返回 nil 字典。
    【解决方案3】:

    为了阅读 PLIST,我将逻辑封装在单例中。 就我而言,我想阅读文件 URLs.plist。

    class URLs {
    
        class var sharedInstance: URLs {
            struct Singleton {
                static let instance = URLs()
            }
            return Singleton.instance
        }
    
        private var urls: NSDictionary!
    
        required init() {
            let filePath = NSBundle.mainBundle().pathForResource("URLs", ofType: "plist")!
            self.urls = NSDictionary(contentsOfFile:filePath)
        }
    
        var backendBaseUrl: String {
            get {
                return urls["BackendBaseUrl"] as! String
            }
        }
    
        var locationEndpoint: String {
            get {
                return urls["LocationEndpoint"] as! String
            }
        }
    
    }
    

    无论您需要在何处访问其中一个 URL,您只需:

    URLs.sharedInstance.backendBaseUrl
    

    这适用于 Xcode 7.1 和 Swift 2.1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多