简体   繁体   中英

What is the best way for a class to listen to events in an object it has instantiated? (Swift)

If I have a class A and a class B , how do I listen in class A for an event that happens in an instance of B ?

class A {
  init() {
    var b = B()
    // somehow listen for events that happen in b then call somethingHappened()
  }

  func somethingHappened() {
    // 
  }
}

class B {
   init() {
     doSomething()
   }

   func doSomething() {
      // dispatch event
   } 
}

The way I am thinking to do this is just to use NSNotificationCenter to broadcast the event, but I'm not sure if this is the right way to do it. Seems easy enough. Is there another way to listen events in the instance of class B?

The NotificationCenter can definitely be used for things like this. But if you have only one instance that needs to listen to the events, you can also use the delegate pattern which is also very common in the frameworks.

// Create a protocol
protocol DoSomethingDelegate {
    func doneSomething()
}

// Add this to class B
var theDelegate: DoSomethingDelegate?
// somewhere in doSomething()
theDelegate?.domeSomething()

// in class A after creating B
b.theDelegate = self // or add this to the init method. However you'd like to do this.

The Adapting Design Patterns section from the documentation may also help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM