Selectors or Blocks for callbacks in an Objective-C library

后端 未结 4 1130
庸人自扰
庸人自扰 2021-02-02 12:35

Question

We\'re developing a custom EventEmitter inspired message system in Objective-C. For listeners to provide callbacks, should we require blocks or selectors and

4条回答
  •  遇见更好的自我
    2021-02-02 13:21

    A thing about a library is, that you can only to some extend anticipate, how it will be used. so you need to provide a solution, that is as simple and open as possible — and familiar to the users.

    • For me all this fits best to delegation. Although you are right, that it can only have on listener (delegate), this means no limitation, as the user can write a class as delegate, that knows about all desired listeners and informs them. Of course you can provide a registering class. that will call the delegate methods on all registered objects.
    • Blocks are as good.
    • what you name selectors is called target/action and simple yet powerful.
    • KVO seems to be a not optimal solution for me as-well, as it would possibly weaken encapsulation, or lead to a wrog mental model of how using your library's classes.
    • NSNotifications are nice to inform about certain events, but the users should not be forced to use them, as they are quite informal. and your classes wont be able to know, if there is someone tuned-in.

    some useful thoughts on API-Design: http://mattgemmell.com/2012/05/24/api-design/

提交回复
热议问题