iOS - 从作为参数传递的块内部获取变量 [英] iOS - Getting a variable from inside a block passed as a parameter

查看:118
本文介绍了iOS - 从作为参数传递的块内部获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在敲我的头一会儿,但似乎找不到我在找的东西。基本上我在类A中有以下方法声明。

I've been banging my head on this for a while now, but couldn't seem to find what I was looking for. Basically I have the following method declaration in class A.

- (void)doSomethingCoolWithThisBlock:(void (^)(void))block 

在类B中,当我在块部分中调用此方法时, p>

In class B, when I call this method something like the following in the block part:

UILabel *myLabel = [[UILabel alloc] init];
UITextField *myField = [[UITextField alloc] init];

等。

在执行我的 doSomethingCoolWithThisBlock 如何可以解剖块内的内容,并得到说UILabel例如?

My question is, in the implementation of my doSomethingCoolWithThisBlockhow can I dissect what's inside the block and get say the UILabel for example?

推荐答案

简单的答案是,你不能;如果你想传递一个 UILabel 到该方法,它应该接受一个参数类型 UILabel * 你想要作为单独的参数传递的东西,或者某种容器类型的一个参数 - 可能是你自己的自定义协议包含所有的东西)。

The short answer is that you can't; if you want to pass an UILabel to the method, it should take an argument of type UILabel * (and any other things you want to pass as separate arguments, or one argument of some sort of container type—possibly of your own custom protocol—containing all the things).

但是如果你只需要在块内传递一个东西,你当然可以让块返回(例如,将类型更改为(UILabel *)(^)(void)然后在块的末尾做 return myLabel; )。更复杂的方法是使块作为指针的指针(例如, UILabel ** ),然后从块内分配给那些,但它不'看起来像这样会有意义。

But if you only want to pass one thing from within the block you can of course make the block return something (e.g., change the type to (UILabel *)(^)(void) and then at the end of the block do return myLabel;). A more convoluted way would be to make the block take as arguments pointers to pointers (e.g., UILabel **) and then assign from within the block to those, but it doesn't look like this would make much sense.

这篇关于iOS - 从作为参数传递的块内部获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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