Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when does prepareForSegue get called?

Tags:

xcode

ios

swift

So here is my situation, I have two view controllers: viewControllerA and tableViewControllerB. On my viewControllerA, I have a button. And when it gets pressed, it will call

self.performSegueWithIdentifier("toControllerB", sender: self)

moreover, I wrote a prepareforSegue function that looks like the following:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if (segue.identifier == "toControllerB"){

        var controllerB = segue.destinationViewController as tableViewControllerB
        controllerB.event = self.event
    }

And in my tableViewControllerB I have a function looks like the following

var event = nil
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    self.viewDidLoad()
    var cell = tableView.dequeueReusableCellWithIdentifier("controllerBCell") as? ControllerBCell ?? ControllerBCell()
    //some code
    print(event)
    return cell

}

And when I run my app, it seems like this tableview function gets called before the prepareforSegue function in ControllerA. And thus the "event" variable is nil. Therefore, I am wondering is it possible to call prepareforSegue function before this tableview function in controllerB?

Thanks

like image 705
AdamXiaotCao Avatar asked Mar 16 '23 12:03

AdamXiaotCao


1 Answers

The chain is something like this.

  1. First prepareForSegue is called
  2. Then viewDidLoad is called
  3. Then cellForRowAtIndexPath is called

I guess the problem is your line

self.viewDidLoad()

This function is called automatically. I just tried rest of the code at my end and it works fine.

like image 97
Shamas S Avatar answered Mar 29 '23 14:03

Shamas S