How to pass a block as an argument into another bl

2019-04-04 16:28发布

I'm trying to define a block that takes a block as an argument.

What's wrong with the following line of code?

id (^cacheResult)(NSString *, id(^)(void)) = ^(NSString *name, id(^)(void)block) {
    NSObject *item = nil;
    block();
    return item;
};

Why does the compiler keep giving errors like Parameter name omitted and Expected ")"?

3条回答
Explosion°爆炸
2楼-- · 2019-04-04 16:41
id (^cacheResult)(NSString *, id(^)(void)) = ^(NSString *name, id(^block)(void)) {
    NSObject *item = nil;
    block();
    return item;
};

Blocks have similar syntax to function pointers. You have to declare block name after the ^

查看更多
看我几分像从前
3楼-- · 2019-04-04 16:43

This is why typedef was invented. Embedding function pointers or block types like this is a pain. Try this instead:

typedef id (^ InnerBlock)(void);
typedef id (^ OuterBlock)(NSString *, InnerBlock);

It'll make working with block types a lot easier to read. :)

查看更多
甜甜的少女心
4楼-- · 2019-04-04 16:45

Did you possibly mean id(^block)(void) on the RHS of the assignment?

查看更多
登录 后发表回答