Executing Blocks From NSArray?

前端 未结 3 1539
囚心锁ツ
囚心锁ツ 2021-01-31 08:35

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?

         


        
3条回答
  •  心在旅途
    2021-01-31 09:01

    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
    

提交回复
热议问题