簡體   English   中英

如何從Swift中的PLIST讀取數據?

[英]How can I read data from a PLIST in Swift?

我正在使用swift從plist文件中讀取數據時遇到問題 我的.plist文件

我的代碼:

        let Chapterpath = NSBundle.mainBundle().pathForResource("chapterMapping", ofType: "plist")
    let dict2 = NSDictionary(contentsOfFile: Chapterpath!)
    let chaptername = dict2?.objectForKey("chapterName")
    let chapterNumber = dict2?.objectForKey("pageNumber")

接下來我試圖將plist數據添加到數組中,我應該簡單地使用

var myArray = [chapterName]

我的問題:上面的代碼是否正確? 或者我錯過了什么,當我嘗試使用println((chapterName))打印plist數據時,我收到了一個錯誤

謝謝

首先,plist中的Root對象是NSArray而不是NSDictionary

其次,如果你想在Foundation Collections上使用KVC(我不相信這適用於Swift的數組),你需要調用valueForKeyPath

let chapterPath = NSBundle.mainBundle().pathForResource("chapterMapping", ofType: "plist")
if let arrayOfItems: [AnyObject] = NSArray(contentsOfFile: chapterPath!) {
    let chapterNames: [String] = arrayOfItems.valueForKeyPath("chapterName") as NSArray as [String]
    let pageNumbers: [Int] = arrayOfItems.valueForKeyPath("pageNumber") as NSArray as [Int]
}

第三,快速執行此操作的方法是使用map函數,但是arrayOfItems需要是一個強定義的類型,它可能比它的價值更多。 例:

let array: [ChapterMetaData] = // define it here
let chapterImages = array.map { $0.chapterImage }

正如你所說,你有一個包含多個元素的數組。 objectForKey不搜索大廳樹級別,並為您提供名稱的第一個級別。 你有多個值必須包含一個循環。 請嘗試以下方法:

var Chapterpath:NSString = NSBundle.mainBundle().pathForResource("chapterMapping", ofType: "plist");
var chapters:NSArray = NSArray(contentsOfFile: Chapterpath);

for chapter in chapters {
    let chaptername = chapter["chapterName"]
    let chapterNumber = chapter["pageNumber"]
    println(chaptername);
}

使用以下代碼將Plist數據讀取到NSArray

let path = NSBundle.mainBundle().pathForResource(plistName, ofType: "plist")
var list = NSArray(contentsOfFile: path!) as [[String:String]]

解析項目中AppConfig.plist文件的最簡單方法:

var dictionaryObj: NSDictionary?
if let filePath = NSBundle.mainBundle().pathForResource("AppConfig", ofType: "plist") 
{
    dictionaryObj = NSDictionary(contentsOfFile: filePath)
}
if let dict = dictionaryObj 
{
    //parse it as NSDictionary
}
else
{
    //dictionaryObj is nil or doesn't contain anything.
}

如果Plist Root是數組,則可以使用NSArray:

let path = NSBundle.mainBundle().pathForResource("OrderHelper", ofType: "plist")
let myArray = NSArray(contentsOfFile: path!)

如果Plist Root是Dictionary,您可以使用NSDictionary:

let path = NSBundle.mainBundle().pathForResource("OrderHelper", ofType: "plist") {
let myDict = NSDictionary(contentsOfFile: path!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM