C object delegate or C-style block callback?

I am developing a class that will "fire events" whenever something happens. These events are generally not UI related. I am wondering what is the best way to do this? I studied either:

Delegates

I define the delegate class, accept the delegate in the init function, and call the methods in the delegate class when an event occurs.

C-style blocks

I define a pointer to a function and accept the function in the init function. I will call it when the event happens.

In both cases, I may need to process several "sources", so I need an array of delegates or blocks.

I noticed that in iOS programming, delegates tend to prefer especially for user interface interfaces. But I come from functional programming, where I’m definitely comfortable taking function points and skipping lambdas at the call site, and I like that the compiler handles dragging variables for you, and you usually need a smaller class state. But I see that many iOS developers use delegates.

What is the generally preferred mechanism in iOS for this?

+8
c lambda ios objective-c delegates
source share
3 answers

Each has its own application.

Delegates should be used when there are several β€œevents” to notify the delegate and / or when the class should receive data from the delegate. A good example is a UITableView .

A block is best used when there is only one (or maybe two) event. A good example of this is the termination block (and possibly the failure block). A good example is NSURLConnection sendAsynchronousRequest:queue:completionHandler:

The third option is notifications. This is best used if there are several (and unknown) stakeholders in the event (s). The other two are only useful when there is one (and known) stakeholder.

+18
source share

Using delegates means a closer connection from an architectural point of view than using simple callback blocks. And for non-complicated cases, delegates may be redundant.

Saving blocks in some container is normal, but you should think about the possibility of deleting them at some point later (this will require some work), I mean an additional interface for deleting an already added handler.

0
source share

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

0
source share

All Articles