iOS - Getting a variable from inside a block passe

2019-07-25 18:41发布

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 

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];

etc.

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

1条回答
三岁会撩人
2楼-- · 2019-07-25 19:12

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).

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.

查看更多
登录 后发表回答