10

I have my Swift class as the simple code below:

class FavoriteView: UIView {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    convenience init() {
        self.init(frame: CGRectZero)
    }
    private func commonInit() {
        // init something
    }

    // MY PROBLEM IS HERE
    var favoriteCount: Int = 0 {
        didSet {
            // update the view
        }
    }
}

The logic is whenever the favoriteCount is set to a new value, the code in didSet is run.

It runs well. But the problem is that code (in didSet) is not run for the very first time. I mean when a new FavoriteView instance is initialized, I assume it to run also, but it's not.

Is there any way to run that code (in didSet) for the first time.

Thank you!

vietstone
  • 8,784
  • 16
  • 52
  • 79

1 Answers1

12

didSet observer not invoked with default values, as well as it not invoked when you setting up properties in init methods (due to self not initialized yet). You may write separated method updateView and invoke it in init method and in didSet observer.

private func commonInit() {
    updateView()
    // init something
}

// MY PROBLEM IS HERE
var favoriteCount: Int = 0 {
    didSet {
        updateView()
    }
}

func updateView() {
    //code that you wanted to place in observer
}
Yury
  • 6,044
  • 3
  • 19
  • 41