目标C回调与块 [英] Objective C callbacks with blocks

查看:222
本文介绍了目标C回调与块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过SO的各种答案,但不能完全弄清楚这一切如何实际运作。

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

我所拥有的是一个GameEngine包含可触摸的元素,我想要的是当一个元素被触摸时,它触发了一个我被感动的事件,GameEngine倾听并妥善处理。

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.

在C#中,我将使用代理/事件执行此操作,但似乎找不到使用块的体面对象。 - 我想使用块,因为它更像我习惯的C#中的匿名函数。

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.

在C#中,我只需要做一些像下面这样的事情,在客观上c似乎我需要写一个代码页来获得同样的事情?

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 }

根据Driis的答案进行编辑:

Edit based on Driis' answer:

声明

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


推荐答案

在Objective-C中看起来像:

In Objective-C, that would look something like:

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

假设touch是适当的块类型的属性。如果您重新使用块类型(在C#中考虑Func),那么对于typedef它是有意义的,因为ObjC中的块声明往往很难读取。

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.

当您使用稍微更优雅的块/ lambda语法的另一种语言来,块语法在Objective-C中得到一些时间。要学习和参考,看到这个以前的答案,这帮助了我很多。

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.

对于typedef一个被触摸的类型,你可以使用以下的东西:

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.

这篇关于目标C回调与块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆