简体   繁体   中英

Cannot get data into UITableView in MasterViewController

I cannot get my .plist file to populate my table view in the masterviewcontroller. I am following a book and the code is exactly as written in the book but I am getting EXC_BAD_INSTRUCTION on thread 1 when running the code.

var detailViewController: DetailViewController? = nil
var plantNames: [[String: String]]!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

let path = NSBundle.mainBundle().pathForResource("plantList", ofType: "plist")!
let plantInfo = NSDictionary(contentsOfFile: path)!
plantNames = plantInfo["plants"]! as! [[String: String]]

I get the error on the final line. As far as I can tell, my .plist file matches everything that it would need to. If that needs to be posted as well then let me know.

Any help is greatly appreciated!

Added .plist XML

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"    "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>plants</key>
<array>
    <dict>
        <key>name</key>
        <string>Lily</string>
        <key>sunlight</key>
        <integer>30</integer>
        <key>water</key>
        <integer>40</integer>
    </dict>
    <dict>
        <key>water</key>
        <integer>5</integer>
        <key>sunlight</key>
        <integer>80</integer>
        <key>name</key>
        <string>Cactus</string>
    </dict>
    <dict>
        <key>sunlight</key>
        <integer>100</integer>
        <key>name</key>
        <string>Bonsai Tree</string>
        <key>water</key>
        <integer>50</integer>
    </dict>
</array>

The values in the dictionary contain String and Int types so you have to declare plantNames as [[String:AnyObject]] and a data source array is supposed to be always non-optional.

var plantNames: [[String: AnyObject]]()

...

plantNames = plantInfo["plants"] as! [[String: AnyObject]]

But now you have to cast any value you retrieve from the dictionary to String or Int .

Side-note: When forced downcasting a type the exclamation mark after the key subscription is not needed.

Alternatively change all Int types to String in the property list file to avoid type casting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM