Objective C delegate or C-style block callback?

前端 未结 3 1397
花落未央
花落未央 2021-02-09 02:46

I am designing a class that will \"fire events\" whenever something occurs. These events tend to be non-UI related. I\'m wondering what the best method for doing so is. I\'ve be

相关标签:
3条回答
  • 2021-02-09 03:04

    Using delegates means more tightly coupling in terms of architecture than using simple callback blocks. And for non-complex cases delegates can be an overkill.

    Storing blocks in some container is just ok, but you should think ahead about possibility of removing them at some point later (this will require some work), I mean an additional interface for removing of an already added handler.

    0 讨论(0)
  • 2021-02-09 03:12

    For your use case NSNotification seems to be the best choice. Objects that need those events then can register for those notifications.

    0 讨论(0)
  • 2021-02-09 03:19

    Each has its use.

    Delegates should be used when there are multiple "events" to tell the delegate about and/or when the class needs to get data from the delegate. A good example is with UITableView.

    A block is best used when there is only one (or maybe two) event. A completion block (and maybe a failure block) are a good example of this. A good example is with NSURLConnection sendAsynchronousRequest:queue:completionHandler:.

    A 3rd option is notifications. This is best used when there are possibly multiple (and unknown) interested parties in the event(s). The other two are only useful when there is one (and known) interested party.

    0 讨论(0)
提交回复
热议问题