Replacing delegates with blocks
I recently started learning Objective C and came across blocks / closures. They are very similar to Java Anonymous Inner Classes. I read somewhere that Blocks can be used to replace delegates. This confuses me, since in the case of delegation you are signaling the method when a specific task completes, how can delegates be replaced with blocks?
For example, in Java, delegates are like:
button.addClickListener(new ButtonClickEvent(){
void foo(){
// some code
}
});
In this case, ButtonCLickEvent is a protocol or Java interface. How can this be represented as blocks in Objective C?
source to share
If you are asking whether an object conforming to a specific delegate protocol that has been set as delegate
in some other object can be replaced with a block after some simple scrolling, I would say the answer is no.
Blocks
are just a kind of extended function pointers that can be used as callbacks. There is no mutual concept in Java, not even java8 Function Objects, because they are valid Object
with the same method (I'm sure you are familiar with the concept of functional interfaces).
But that doesn't mean it Blocks
can't be used as callbacks to respond to events, but you will need some kind of adapter that forwards the normal delegation method specified by a specific delegation protocol to the callback block you configured.
An extremely nice example of building something like this is provided by the ReactiveCocoa library , using it you should be able to do something like this:
self.button.rac_command = [[RACCommand alloc] initWithSignalBlock:^(id _) {
NSLog(@"button was pressed!");
return [RACSignal empty];
}];
I am not explaining how it works (it RACSignal
is an abstraction representing the flow of events), but I think you can easily grasp the essence of what it does, really compact.
Update:
For more information on how blocks are implemented in the Foundation SDK see this post . Also check this post from Mike Ash for scripting examples .
source to share
I find it better to use a library.
For example SHUIKitBlocks .
If you need a block for a button, check SHControlBlocks .
source to share