Objective C callbacks with blocks

2019-09-20 05:31发布

问题:

I have looked at various answers on SO for this but can't quite get my head around how it all actually works.

What I have is a GameEngine that contains touchable elements, what I want is for when an element is touched it fires off a "I have been touched" event that the GameEngine listens for and deals with appropriately.

In C# I'd do this with delegates/events but can't seem to find a decent obj c equivalent that uses blocks. - I want to use Blocks as it more akin to anonymous functions in C# which I am used to.

In C# I'd simply do something like the following, in objective c it seems I need to write a page of code to get the same thing working?

touchableObject.touched += (o) => { handler code yay }

Edit based on Driis' answer:

Declaration

typedef void (^CircleTouchedHandler)(id parameter);

@interface CircleView : UIView{
}

@property CircleTouchedHandler Touched;

How to call it and pass myself as a parameter?

[self Touched(self)]; // this doesnt work

回答1:

In Objective-C, that would look something like:

touchableObject.touched = ^(id o) { /* handler code */ };

Assuming touched is a property of an appropiate block type. If you re-use a block type (think of Func in C#), it makes sense to typedef it, since a block declaration in ObjC tends to become difficult to read very quickly.

The block syntax gets some time to get used to in Objective-C when you are coming from another language with slightly more elegant block/lambda syntax. To learn and as a reference, see this previous answer, which has helped me a lot.

To typedef a type for touched, you would use something like:

typedef void (^Handler)(id parameter);

Then simply declare the touched property as type handler.