Objective C callbacks with blocks

佐手、 提交于 2019-12-13 23:41:22

问题


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.



来源:https://stackoverflow.com/questions/19876468/objective-c-callbacks-with-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!