Search code examples
iosswiftnsnotificationcenterkey-value-observing

How one model can notify another model for specific property has changed?


Context, an iOS app using UIKit and MVC.

Model A has a singleton object, and one of its property value (foo in this case) can be changed during the runtime. Model B has a property, Model C, that is initialized using the property value of Model A.

class ModelA {
    private(set) var foo: CustomObjectClassName

    static let shared = ModelA()
}

class ModelB {
    private var bar: ModelC

    init() {
        self.bar = ModelC(ModelA.shared.foo)
    }

    // TODO: Observer `foo` value change in Model A and then
    // reinit ModelC to replace the old `bar` object
}

What is the common design pattern or mechanism that should be used to let Model B know about property change in Model A and re-initialize its own property?

I found two patterns that can be used; however, the more I read about them, they seem to be designed for communication between Model and Controller.

  • NotificationCenter (Notification & Observer)
  • Key-value Observing

Related Information


Solution

  • Thanks for El Tomato comment, delegation can be a pattern be used.

    A delegation pattern would work since in my case Model A is only used by a single entity Model B.

    protocol ModelADelegate {
        func fooDidChange() -> Void
    }
    
    class ModelA {
        public var delegate: ModelADelegate?
    
        private(set) var foo: CustomObjectClassName {
            didSet {
                delegate.fooDidChange()
            }
        }
       
        static let shared = ModelA()
    }
    
    class ModelB, ModelADelegate {
        private var bar: ModelC
    
        init() {
            ModelA.shared.delegate = self
    
            self.bar = ModelC(ModelA.shared.foo)
        }
    
        func fooDidChange() {
            self.bar = ModelC(ModelA.shared.foo)    
        }
    }