从NSArray执行块? [英] Executing Blocks From NSArray?
本文介绍了从NSArray执行块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是想,因为你可以处理块像对象,如果我创建两个,然后将它们添加到一个NSArray是有办法从数组中执行他们。
I was just thinking, as you can treat Blocks like objects if I create two of them and then add them to an NSArray is there a way to execute them from the array?
int (^Block_001)(void) = ^{ return 101; };
int (^Block_002)(void) = ^{ return 202; };
NSArray *array = [NSArray arrayWithObjects:Block_001, Block_002, nil];
编辑:更新为了清楚Per @ davedelong的优秀答案
Update for clarity Per @davedelong's excellent answer
int (^Block_001)(void) = [^{ return 101; } copy];
int (^Block_002)(void) = [^{ return 202; } copy];
NSArray *array = [NSArray arrayWithObjects:Block_001, Block_002, nil];
[Block_001 release];
[Block_002 release];
推荐答案
当然,你只需调用()
像任何其他块,但你需要类型转换从 NSArray
检索的值。这里是一个例子(添加了typedef,因为否则我的头疼):
Sure, you just invoke it with ()
like any other block, but you need to typecast the value you retrieve from NSArray
. Here's an example (with an added typedef, because otherwise my head hurts):
typedef int (^IntBlock)(void);
IntBlock Block_001 = ^{ return 101; };
IntBlock Block_002 = ^{ return 202; };
NSArray *array = [NSArray arrayWithObjects:Block_001, Block_002, nil];
int x = ((IntBlock)[array objectAtIndex:0]) (); // now x == 101
这篇关于从NSArray执行块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文