开发者

Function that returns a function

开发者 https://www.devze.com 2023-03-20 05:15 出处:网络
How to assign and subsequently call a function that returns a function to a local variable in Objective-C?

How to assign and subsequently call a function that returns a function to a local variable in Objective-C?

UPDATE:

I've come up with the following but it's still not right I'm afraid:

(void (^)()) (^loadedCallback) () = (void (^)())开发者_Python百科 ^(){
    @synchronized (synchronizer) {
        semaphore++;
    }
      return Block_copy(^{
          @synchronized (synchronizer) {
              semaphore--;
              if (semaphore == 0) {
                  onAllLoaded();
              }
          }
      }); };


First, you need to understand the function pointer declaration syntax. It's the same for blocks, except that it's a ^ instead of a *.

Then, you need to create a block and return a copy of it, and assign that to a correctly-declared variable.

typedef NSArray* (^my_block_type_t)(int, float);

my_block_type_t createBlock()
{
    my_block_type_t block = ^(int a, float b)
    {
        return [NSArray array];
    };
    return Block_copy(block);
}

/* snip */
my_block_type_t theBlock = createBlock();
theBlock();
Block_release(theBlock);

EDIT to address OP's edit: typedefs are typically used to make code easier to read. In the case of blocks and function pointers, it also makes it easier to write. There is a built-in typedef (dispatch_block_t) for blocks that accept no arguments and return void; you should use it. You should also make as many typedefs as you need to avoid having to use the ugly declaration syntax function pointers otherwise force onto your code.

typedef dispatch_block_t (^block_creator_t)();

block_creator_t loadedCallback = ^{
    @synchronized (synchronizer)
    {
        semaphore++;
    }

    dispatch_block_t result = ^{
        @synchronized (synchronizer)
        {
            semaphore--;
            if (semaphore == 0)
                onAllLoaded();
        }
    };

    return Block_copy(result);
};
0

精彩评论

暂无评论...
验证码 换一张
取 消