aleclarson / emitter-kit

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

Add `AssociatedListeners` class #46

Open aleclarson opened 6 years ago

aleclarson commented 6 years ago

Currently, targeted listeners must be manually retained by their target if you want the listeners to get released when/if their target gets released. If you don't do that, your code may be retaining listeners whose target has long been released. This means wasted memory, because those listeners will never be triggered.

The AssociatedListeners class would use objc_setAssociatedObject to attach an array (of strong pointers to all associated listeners) to the appropriate target. You would no longer have to manually retain indefinite listeners, since they would be released when the target is released.

Additionally, a helper method would be added to the Event class called getListeners(target) for retrieving the array of associated listeners. You could use this method to remove associated listeners any time before the target is released.

I'm interested in finding out if anyone thinks this is a problem worth solving. Thanks.

mickeyl commented 3 years ago

Definitely a good point, since often it‘s a bit of a burden to retain the listener. Then again, using ObjC-associations would only work for Apple-platforms, since there is no such runtime available elsewhere.