aleclarson / emitter-kit

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

You should always retain a list of listeners #27

Closed SamDecrock closed 8 years ago

SamDecrock commented 8 years ago

Just an extra reason to store the listeners in an array in your object is because when that object is deallocated, the listeners are deallocated as well. Which leaves no listeners hanging in "thin air".

For example:

class SomeTemporaryClass {
    var listeners = [Listener]()

    init(someEvent: Event<String>) {
        listeners += someEvent.on { (str) -> Void in
            print("someEvent was triggered")
        }
    }

    deinit {
        print("instance of SomeTemporaryClass was deallocated")
    }
}

class ViewController: UIViewController {
    var temp: SomeTemporaryClass?

    override func viewDidLoad() {
        super.viewDidLoad()

        let someEvent = Event<String>()
        temp = SomeTemporaryClass(someEvent: someEvent)
        temp = nil // deallocate temp and it's listeners will be deallocated too :-)
        someEvent.emit("hello")

    }
}
SamDecrock commented 8 years ago

Ah, Ok, apparently I must always retain an "on"-listener. Good :-)

phimage commented 8 years ago

I think using attributes warn_unused_result on on methods will be a good things