Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a block as an argument into another block in Objective C

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 ")"?

like image 271
Tony Avatar asked Dec 30 '11 18:12

Tony


2 Answers

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 ^

like image 101
Max Avatar answered Nov 14 '22 21:11

Max


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

like image 10
Jonathan Grynspan Avatar answered Nov 14 '22 21:11

Jonathan Grynspan