0

I'm looking to get my variable content in my awakeFromNib function in my custom cell.

Actually, I pass my data like this :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "question_cell", for: indexPath) as! QuestionsCell

    cell.answers = ["Answer 1", "Answer 2"]

    return cell
}

In my QuestionCell file, I've got my variable declared like this : var answers = [String]()

And When I want to print my answer variable, I've got an empty array in the output console []

override func awakeFromNib() {
    super.awakeFromNib()

    print("HELLOOOOOOOOOOOO !!!!!!!!!!!!")
    print(answers)
}

Could you please help me to solve this ? Thank you

noxo.
  • 116
  • 10
  • 1
    `cellForRowAt` is called when the cell is to be drawn. `awakeFromNib` is called when the viewController is decoded from the storyboard. `awakeFromNib` happens first. It doesn't happen again. So answers at the point is going to be `nil`. You real question is **when is `awakeFromNib` called?** I've linked a similar question for you – mfaani Jan 09 '20 at 00:44
  • Does this answer your question? [When does awakeFromNib get called?](https://stackoverflow.com/questions/9122344/when-does-awakefromnib-get-called) – mfaani Jan 09 '20 at 00:44

1 Answers1

2

awakeFromNib() Would be called before the line cell.answers = ["Answer 1", "Answer 2"] in cellForRowAt is called.

To respond to changes to answers, you can do the property observer didSet to your variable definition.

Just change var answers = [String]() to:

var answers = [String]() {
    didSet {
        print(answers)
    }
}
aasatt
  • 600
  • 3
  • 16
  • 1
    Also, `awakeFromNib` is only called when the cell is created, not when it is reused, so even if the property was set before that function it would only be called once – Paulw11 Jan 09 '20 at 02:05
  • Thank you for your help. I already did it but I forgot to make a ReloadData for my tableView so The content wasn't loaded. Thanks for your help – noxo. Jan 09 '20 at 10:36