aleclarson / emitter-kit

Type-safe event handling for Swift
MIT License
567 stars 71 forks source link

notification + target seems to not be working #23

Closed mateusmaso closed 9 years ago

mateusmaso commented 9 years ago

works:

NSNotificationCenter.defaultCenter().addObserverForName(NSPopoverWillCloseNotification, object: self.popover, queue: nil, usingBlock: { _ in
  self.statusItemView.highlighted = false
})

don't work:

Notification(NSPopoverWillCloseNotification).on(self.popover, { data in
  self.statusItemView.highlighted = false
})

am I doing something wrong?

aleclarson commented 9 years ago
// In the class declaration:
//
var listeners = [Listener]()

// In one of the class's methods:
//
self.listeners += Notification(NSPopoverWillCloseNotification).on(self.popover) {
  [unowned self] data in
  self.statusItemView.highlighted = false
}

If you don't retain the returned Listener, it will deinit before it can "hear" the emitted NSNotification.

Also, notice the [unowned self] that I added. This prevents a memory leak, but there's a catch. You must make sure the returned Listener deinits before self does. Otherwise, your program will crash when trying to access self after hearing the emitted NSNotification.

Hope that all makes sense. Cheers!