beasone
beasone

Reputation: 1085

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

Upvotes: 0

Views: 119

Answers (2)

Beau Nouvelle
Beau Nouvelle

Reputation: 7252

Providing your file name is correct, and your plist has been added to the bundle:

You need to make sure your file is the type you're expecting.

For example. The root of your plist is an Array, and you're looking to get a Dictionary out of it.

So lets rewrite your code:

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

Upvotes: 0

larva
larva

Reputation: 5148

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

Upvotes: 3

Related Questions