2015-11-04 47 views
0

enter image description here
這是我的代碼。但是myDictnil。文件名是正確的,我已經檢查了很多次。爲什麼我無法從plist讀取數據?

var myDict: NSDictionary? 
    if let path = NSBundle.mainBundle().pathForResource("CatData", ofType: "plist") { 
     myDict = NSDictionary(contentsOfFile: path) 
    } 
    if let dict = myDict { 
     print("print something") 
    } 
+0

可以顯示CatData.plist格式? – larva

+2

你的plist的根目錄不是字典 – Todd

回答

3

您的plist是字典的數組所以儘量

var myArray: NSArray? 
    if let path = NSBundle.mainBundle().pathForResource("Categories", ofType: "plist") { 
     myArray = NSArray(contentsOfFile: path) 
    } 
    if let array = myArray { 
     for item: AnyObject in array { 
      if let item = item as? NSDictionary { 
       if let categoryTitle = item["CategoryTitle"] as? NSString { 
        print("categoryTitle = ", categoryTitle) 
       } 
       if let imageNames = item["ImageNames"] as? NSArray { 
        print("imageNames = ", imageNames) 
       } 
      } 
     } 
    } 
+0

它是一個字典數組。 – beasone

+0

@beasone是你可以在數組中獲得plist內容數據,然後繼續解析它 – larva

+0

爲什麼要投票。代碼是錯誤的? – larva

0

提供您的文件名是正確的,你的plist已被添加到包:

你需要確保你的文件是你希望的類型。

例如。你的plist的根是一個數組,你正在尋找一本字典。

所以,讓我們重寫代碼:

var myArray: Array? { 
    if let path = NSBundle.mainBundle().pathForResource("CatData", ofType: "plist") { 
     myArray = NSArray(contentsOfFile: path) as! [[String:AnyObject]] 
    } 
    if let array = myArray { 
     print("print something") 
    } 
} 
+0

看來我的plist是一個字典數組。我怎樣才能將數據存入字典數組? – beasone

+0

var dict:Array 像這樣? – beasone

+0

給我幾分鐘,做一些改變 –