为什么我不能从 plist 读取数据?

why I cannot read data from plist?


这是我的代码的一部分。但是 myDictnil。文件名 right.I 已检查多次。

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

如果您的文件名正确,并且您的 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")
    }
}

你的 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)
                }
            }
        }
    }