Search code examples
iosswiftplist

why I cannot read data from plist?


enter image description here
This is part my code. But myDict is nil. The filename is right.I already checked for many times.

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

Solution

  • your plist is array of dictionary so try

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