user2023106
user2023106

Reputation:

Calling object from viewdidload in swift

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let path = NSBundle.mainBundle().pathForResource("TableRowInfo", ofType: "plist")!
    let dict = NSDictionary(contentsOfFile:path)!

    var artists: AnyObject = dict.objectForKey("Artist")!
    var stages: AnyObject = dict.objectForKey("Stage")!
    println(artists)
    println(stages)
}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return artists.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("InfoCell", forIndexPath: indexPath) as? UITableViewCell

    if cell == nil {
        cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "InfoCell")
        cell!.accessoryType = .DisclosureIndicator
    }

    return cell!
}
}

Hey all,

I'm new to swift so just experimenting with some things. What I'm trying to do is filling my table with content from a plist file. I know this isn't the best way! I already loaded the list successfully. My println(artists) returns what I want as well does the stages. The only problem is if I call artists or stages outside my viewDidLoad function it doesn't work. Why is that and how do I solve it?

Thanks in advance.

Greets,

Wouter

Upvotes: 0

Views: 2081

Answers (1)

mhaddl
mhaddl

Reputation: 955

The variables "artists" and "stages" do not exists outside of the viewDidLoad-Function scope. You have to define them as properties to access them outside of the viewDidLoad-function. Like this

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {


    var artists: AnyObject?
    var stages: AnyObject?

    override func viewDidLoad() {
        ...
        artists: AnyObject = dict.objectForKey("Artist")
        ...
    }

Upvotes: 3

Related Questions