Wraith
Wraith

Reputation: 501

Why can't I assign value on didSet?

I have two view. On my first view i create some data and send to other view lets name view2. So my view1 has code:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showUserDetail" {
        (segue.destinationViewController as! UserDetailTableViewController).detailContact = detailCoversationContact
    }
}

In my detailCoversationContact i have detail about this one user, this detail like number, nick etc. Now as i expect this data are put to variable detailContact in my view2

And this is my cod in view2 this code is work:

class UserDetailTableViewController: UITableViewController {

@IBOutlet weak var nickNameLabel: UILabel!

var nickMy: String = ""

var detailContact: AnyObject? {
    didSet {
    // Update the user interface for the detail item.
        if let detail = self.detailContact {
            self.nickMy = (detail.valueForKey("nickName") as? String)!
        }
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    nickNameLabel.text = nickMy      
}

}

When i send data to detailContact' i check is didSet if yes i set my nickMy and this is work. But what is first ? setting my var or viewDidLoad?

this is my code and not working and can someone explain why ?

class UserDetailTableViewController: UITableViewController {

    @IBOutlet weak var nickNameLabel: UILabel!

    var detailContact: AnyObject? {
        didSet {
        // Update the user interface for the detail item.
            if let detail = self.detailContact {
                   self.title = detail.valueForKey("nickName") as? String
                   self.nickNameLabel?.text = (detail.valueForKey("nickName") as? String)!
            }
        }
    }

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

}

Ok this is self.title and work i see the name of user but title is from tableView. But my nickNameLabel is not change ? why ?

Upvotes: 3

Views: 503

Answers (1)

vacawama
vacawama

Reputation: 154583

At the time of prepareForSegue, the IBOutlets have not been set up yet. So, self.nickNameLabel is still nil, and optional chaining makes self.nickNameLabel?.text = ... safely do nothing.

Set the value in viewDidLoad() when the IBOutlets have been set up:

override func viewDidLoad() {
    super.viewDidLoad()
    self.nickNameLabel?.text = (detail.valueForKey("nickName") as? String)!
}

Alternatively, you can trigger didSet by setting the detailContact to itself in viewDidLoad(). You have to trick Swift in order to do this because it thinks assigning detailContact to itself does nothing:

override func viewDidLoad() {
    super.viewDidLoad()
    detailContact = (detailContact)  // trigger didSet to set up the label
}

Upvotes: 3

Related Questions